How to return SeekBar value to previous activity?

瘦欲@ 提交于 2020-01-05 15:45:54

问题


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



来源:https://stackoverflow.com/questions/33962220/how-to-return-seekbar-value-to-previous-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!