Android从不同的活动更新TextView

时间:2016-10-09 14:14:53

标签: android android-layout

我是Android的新手而不是100%确定我的问题的术语是正确的,但现在是。

我有一个TextView的布局,我想反映一个设置。我面临的问题是,设置页面(" customsignalsetup")从我想要更新的TextView所在的页面导航到。如果在设置页面上更改了该选项,并使用Finish()关闭该选项,则TextView尚未更新。但是,如果我关闭页面TextView已打开,请再次打开它,它已更新。

这是我的代码:

TextView更新代码(在设置页面上进行任何更改之前)

settings = getSharedPreferences("CustomSignalSettings", 0);
        TextView CustLabel = (TextView)findViewById(R.id.cunitslabel);
        CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");

代码处理"设置"从菜单按下并切换到设置页面

  public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.custom_signal_setup:
       // Open Settings Page
                Intent intent = new Intent(PLCActivity.this, customsignalsetup.class);
                startActivity(intent);

                return true;
            case R.id.help:
               //get help
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

设置页面代码以更新TextView

    public class customsignalsetup extends AppCompatActivity implements View.OnClickListener {

     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.customplcsettingspopup);

     Button button = (Button) findViewById(R.id.save);
            button.setOnClickListener(this);
     }

     public void onClick(View v) {
           switch(v.getId()){
               case R.id.save:

//THE BELOW LINE IS SUPPOSED TO SET 'CustLabel' TO THE TEXTVIEW TO BE UPDATED
                   TextView CustLabel = (TextView)findViewById(R.id.cunitslabel);

                   SharedPreferences settings = getSharedPreferences("CustomSignalSettings", 0);
                   SharedPreferences.Editor editor = settings.edit();
                   editor.putString("CustomSignalUnit",CusUnit.getText().toString());
                   editor.commit();

// THE BELOW LINE IS SUPPOSED TO UPDATE THE TEXTVIEW ON A DIFFERENT PAGE                  
 CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");

                   finish();
           }
        }


    }

我的代码不会抛出任何错误,但TextView根本不会更新。我假设这是因为加载的活动原始textview还没有结束,只有未来的标签会更新?

由于

1 个答案:

答案 0 :(得分:1)

将此行放在此处,这样您每次都会获得更新的值。

@Override
public void onResume() {
   super.onResume();  // Always call the superclass method first
   CustLabel.setText("Custom (" + settings.getString("CustomSignalUnit", "").toString() + ") =");
}