繁体   English   中英

在Android中恢复活动时维护变量

[英]Maintaining a variable when resuming an Activity in android

我正在开发一个列表应用程序,它基于行ID从数据库中获取信息。 在此页面上还有一个添加事务按钮,单击该按钮可加载新活动。

如果用户单击顶部导航上的主屏幕按钮,但此活动返回时,我的变量尚未保存,则此活动使用NavUtils类返回到列表。 我是否可以在两个屏幕之间保持此变量不变,甚至可以通过NatUtils.navigateUpFromSameTask()将其传递回来?

    public class DisplayAccountActivity extends Activity {

    private long account_id;       

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_display_account);
            // Show the Up button in the action bar.
            setupActionBar();

            // Receive the intent
            Intent intent = getIntent();
            account_id = intent.getLongExtra(MainActivity.ACCOUNT_ID, 0);
    }

    public void addTransaction (View view) {
            Intent intent = new Intent(this, AddTransactionActivity.class);
            startActivity(intent);
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    getActionBar().setDisplayHomeAsUpEnabled(true);
            }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                    NavUtils.navigateUpFromSameTask(this);
                    return true;
            }
            return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
            super.onResume();
            System.out.println("On resume the ID is: "+this.account_id);
    }

    @Override
    protected void onPause() {             
            super.onPause();
            System.out.println("On pause the ID is: "+this.account_id);
    }

   }

您可以将变量设为静态。 然后,您可以在需要重置它时重置它,例如在onCreate中重置它。

您可以使用意图在活动之间传递数据。

在您的第一个活动中:

Intent i= new Intent("com.example.secondActivity");
// Package name and activity
// Intent i= new Intent(MainActivity.this,SecondActivity.Class);
// Explicit intents
i.putExtra("key",mystring);
// Parameter 1 is the key
// Parameter 2 is your value
startActiivty(i);

在第二个活动中检索它:

Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//get the value based on the key
}

编辑:

如果您想保留值,请使用共享首选项

http://developer.android.com/guide/topics/data/data-storage.html#pref

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM