代码之家  ›  专栏  ›  技术社区  ›  ganga

如何在android中保存文本视图?

  •  0
  • ganga  · 技术社区  · 6 年前

    帮助我找到解决方案。下面是我在文本视图中扫描和显示的代码,现在我想以任意格式保存此文本视图。

    下面是我的代码。

    public class MainActivity extends AppCompatActivity {
    TextView tv;
    Button bt;
    String contents="", format="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.contents);
        bt = (Button)findViewById(R.id.save);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent in) {
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, in);
        if (scanningResult != null) {
            try {
                contents = in.getStringExtra("SCAN_RESULT");
                format = in.getStringExtra("SCAN_RESULT_FORMAT");
                tv.setText("Content-" + contents + "\n" + " Format-" + format);
            }
            catch (NullPointerException e){}
        }
    }
    
    public void save(View v){
        if(contents.equals("")){
            Toast.makeText(getApplication(),"Click Camera icon to Scan BarCode",Toast.LENGTH_LONG).show();
        }
        else{
            //search scan result on web
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(contents)));
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_camera:
                IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this);
                scanIntegrator.initiateScan();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    }
    

    如何使用共享首选项实现这一点?

    1 回复  |  直到 6 年前
        1
  •  0
  •   marc_s    6 年前

    将值保存到 SharedPrefence 您可以这样做:

    private static final String PREF_KEY_SOMETHING = "PREF_KEY_SOMETHING";
    
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.edit().putString(PREF_KEY_SOMETHING, yourValue).apply();
    

    要再次检索它,请执行以下操作。

        String yourValueBack = sharedPreferences.getString(PREF_KEY_SOMETHING ,null);