How to return SeekBar value to previous activity?

2019-08-07 19:39发布

问题:

How to return seekBar value from Activity B to Activity A ?

seekBar=(SeekBar)findViewById(R.id.seekBarPercentage);

save.setOnClickListener(new View.OnClickListener()  //return to previous activity {
    @Override
    public void onClick(View v) {
        Intent returnIntent=new Intent();
        Project=project.getSelectedItem().toString(); //spinner value
        Description=description.getText().toString(); //editText value
        // seekBar value ?
        returnIntent.putExtra("Project",Project);
        returnIntent.putExtra("Description",Description);
        setResult(Activity.RESULT_OK,returnIntent);
    }
});

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    int progress = 0;

    @Override
        public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
            progress = progresValue;
            // Toast.makeText(getApplicationContext(), "Changing seekbar's progress", Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            //  Toast.makeText(getApplicationContext(), "Started tracking seekbar", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            progressText.setText("Covered: " + progress + "/" + seekBar.getMax());
            // Toast.makeText(getApplicationContext(), "Stopped tracking seekbar", Toast.LENGTH_SHORT).show();
        }
    });

}

回答1:

  1. Keep the int progress outside the OnSeekBarChangeListener.
  2. Retrieve current progress as progress = seekBar.getProgress().
  3. Similar to returnIntent.putExtra("Description",Description);, put the progress in the Intent as an extra.


回答2:

Additionally to @Anindya Dutta's Answer if you want to persist the data use SharedPreferences

Get SharedPreferences

SharedPreferences prefs = getDefaultSharedPreferences(context);

Read preferences:

String key = "test1_string_pref";
String default = "returned_if_not_defined";
String test1 = prefs.getString(key, default);

To edit and save preferences

SharedPreferences.Edtior editor = prefs.edit(); //Get SharedPref Editor
editor.putString(key, "My String");
editor.commit();

Shorter way to write

prefs.edit().putString(key, "Value").commit();

Additional info for SharedPreferences: JavaDoc and Android Developers Article