如何在 Android 中使用保存的实例状态并通过微调器恢复实例状态?

发布于 2024-11-27 01:56:07 字数 5856 浏览 0 评论 0原文

我的活动中有一个带有选项列表的微调器,

当用户选择一个选项时,我使用 OnItemSelected 适配器来获取所选选项的位置值,并在其中添加了一些 If Else 语句。 If 语句实际上从预定义的数据库中生成一个随机字符串并显示在 TextView 上。

现在我将切换回另一项活动并再次回到此活动。现在的问题是默认情况下仅选择微调器的第一个选项,我需要使用用户最后选择的选项进行更新,并且当活动再次启动时必须运行该选项的功能。

我也做了一些搜索,发现现在可以通过使用 onSaveInstanceStateonRestoreInstanceState 来完成:

  • 我如何使用这两个以及我应该将它们放在 onItemSelected( 内)适配器)还是外部?
  • 如何将用户选择的新位置值更新(或存储)为随机生成的代码?

为了清楚起见,请检查我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_scheduledactivity);

    /**displayed when the activity is launched (this should be 
    updated with the user selected option)**/
    Resources res = getResources();
    myString = res.getStringArray(R.array.normal); 
    String q = myString[rgenerator.nextInt(myString.length)];
    TextView tv = (TextView) findViewById(R.id.text1);
    tv.setText(q);

    //initiating the spinner
      Spinner s = (Spinner) findViewById( R.id.spinner);
      s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
 if (pos == 1){

     //displayed on the time when user selects the option
     Resources res = getResources();
     myString = res.getStringArray(R.array.hardships); 
     String q = myString[rgenerator.nextInt(myString.length)];
     TextView tv = (TextView) findViewById(R.id.text1);
     tv.setText(q);

     }

else {
    //do nothing
     }

编辑的问题:

为了更清楚,我已经编辑了问题。基本上我想做的是,我想用微调器保存用户选择的位置。当用户单击“Thankyou”Button 时,活动将完成,并将在几分钟后由来自不同类的广播接收器调用开始。当活动再次启动时,用户最后选择的选项(上一个活动)必须作为该活动的默认选项。

我认为如果您查看代码,问题在于保存和恢复实例状态。

请看看我的代码:

import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MyScheduledActivity extends Activity {

    private String[] myString;
    private static final Random rgenerator = new Random();
    protected int mPos;
  protected String mSelection;
  String situation[] = {"Normal","Hardship","Sadness","Exam"};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_scheduledactivity);


    if (mPos == 0) {
    Resources res = getResources();
    myString = res.getStringArray(R.array.normal); 
    String q = myString[rgenerator.nextInt(myString.length)];
    TextView tv = (TextView) findViewById(R.id.text1);
    tv.setText(q);
    }

        //selection of the spinner
        Spinner s = (Spinner) findViewById( R.id.spinner);

        // Application of the Array to the Spinner
            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, situation);
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s.setAdapter(spinnerArrayAdapter);

            s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

                    MyScheduledActivity.this.mPos = pos;
                    MyScheduledActivity.this.mSelection = parent.getItemAtPosition(pos).toString();

                    //display toast                     
                    Toast.makeText(parent.getContext(), "The Situation is " +
                    parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();

                    if (mPos == 0){

                        Resources res = getResources();
                        myString = res.getStringArray(R.array.hardships); 
                        String q = myString[rgenerator.nextInt(myString.length)];
                        TextView tv = (TextView) findViewById(R.id.text1);
                        tv.setText(q);

                    }

                    if (mPos == 1){

                        Resources res = getResources();
                        myString = res.getStringArray(R.array.hardships); 
                        String q = myString[rgenerator.nextInt(myString.length)];
                        TextView tv = (TextView) findViewById(R.id.text1);
                        tv.setText(q);

                    }

                    else {
                        //do nothing
                         }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parentView) {
                //do something else
                    return;
                }
                });


    //dismiss button - Thank You
    Button buttonDismiss = (Button)findViewById(R.id.dismiss);

    buttonDismiss.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }});

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putStringArray(mSelection, situation);
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    situation = savedInstanceState.getStringArray("mSelection");
    super.onRestoreInstanceState(savedInstanceState);
}


}

这就是活动看起来

I have a spinner in my activity with a list of options,

When the user selects an option, I have used OnItemSelected adapter to get the position value of the selected option and within that i have added some If Else Statements. The If statement, actually generates a random string from the predefined database and displays on TextView.

Now i will be switching back to another activity and again come back to this activity. Now the problem is by default the first option of the spinner is only selected, I need to update with the last selected option of the user and when the activity starts again that option's functions must be run.

I did some searches too and found that this can be done by using onSaveInstanceState and onRestoreInstanceState now :

  • How do I use these two and where should i put them, inside the onItemSelected(adapter) or Outside?
  • How do I update(or store) the new position value selected by the user to the random generated code?

For clarity please check my code:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_scheduledactivity);

    /**displayed when the activity is launched (this should be 
    updated with the user selected option)**/
    Resources res = getResources();
    myString = res.getStringArray(R.array.normal); 
    String q = myString[rgenerator.nextInt(myString.length)];
    TextView tv = (TextView) findViewById(R.id.text1);
    tv.setText(q);

    //initiating the spinner
      Spinner s = (Spinner) findViewById( R.id.spinner);
      s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
 if (pos == 1){

     //displayed on the time when user selects the option
     Resources res = getResources();
     myString = res.getStringArray(R.array.hardships); 
     String q = myString[rgenerator.nextInt(myString.length)];
     TextView tv = (TextView) findViewById(R.id.text1);
     tv.setText(q);

     }

else {
    //do nothing
     }

EDITED QUESTION:

I have edited the question for more clarity. Basically what I am trying to do is, I want to save the position selected by they user, with the spinner. When the user clicks "Thankyou" Button the activity will finish and will start after few minutes called by a Broadcast receiver from a different class. When the activity starts again the last selected option (previous activity) of the user must be as default in this activity.

I think if you look at the code the problem is in save and restore instance state.

Please have a look at my code:

import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MyScheduledActivity extends Activity {

    private String[] myString;
    private static final Random rgenerator = new Random();
    protected int mPos;
  protected String mSelection;
  String situation[] = {"Normal","Hardship","Sadness","Exam"};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_scheduledactivity);


    if (mPos == 0) {
    Resources res = getResources();
    myString = res.getStringArray(R.array.normal); 
    String q = myString[rgenerator.nextInt(myString.length)];
    TextView tv = (TextView) findViewById(R.id.text1);
    tv.setText(q);
    }

        //selection of the spinner
        Spinner s = (Spinner) findViewById( R.id.spinner);

        // Application of the Array to the Spinner
            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, situation);
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s.setAdapter(spinnerArrayAdapter);

            s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

                    MyScheduledActivity.this.mPos = pos;
                    MyScheduledActivity.this.mSelection = parent.getItemAtPosition(pos).toString();

                    //display toast                     
                    Toast.makeText(parent.getContext(), "The Situation is " +
                    parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();

                    if (mPos == 0){

                        Resources res = getResources();
                        myString = res.getStringArray(R.array.hardships); 
                        String q = myString[rgenerator.nextInt(myString.length)];
                        TextView tv = (TextView) findViewById(R.id.text1);
                        tv.setText(q);

                    }

                    if (mPos == 1){

                        Resources res = getResources();
                        myString = res.getStringArray(R.array.hardships); 
                        String q = myString[rgenerator.nextInt(myString.length)];
                        TextView tv = (TextView) findViewById(R.id.text1);
                        tv.setText(q);

                    }

                    else {
                        //do nothing
                         }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parentView) {
                //do something else
                    return;
                }
                });


    //dismiss button - Thank You
    Button buttonDismiss = (Button)findViewById(R.id.dismiss);

    buttonDismiss.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }});

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putStringArray(mSelection, situation);
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    situation = savedInstanceState.getStringArray("mSelection");
    super.onRestoreInstanceState(savedInstanceState);
}


}

This is how the activity looks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白昼 2024-12-04 01:56:07

在您当前的 Activity 中重写名为 onSaveInstanceState() 的方法并将数据放入捆绑包中。

并重写另一个方法 onRestoreInstanceState() 并从捆绑包中获取这些值......

In your present Activity override a method called onSaveInstanceState() and put your data in bundle.

and override another method onRestoreInstanceState() and get those values from the bundle....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文