1

I have am facing an issue. I don't know it is the way its supposed to be or I am missing something.
I wanted to change the text of the textview from other activity by ...
1. Inflating the layout of other activity.
2. obtaining the textview
3. calling setText() on the textview
I did this but when I switched back to activity which uses that layout the text was the same as previous.
So I took the liberty to check it on a new fresh project with only "hello world" textview on mainactivity and on one other activity to change the text of "hello world" textview.
But I got the same result. The text didn't change. It didn't even give me an exception or anything. Application ran normally. I don't understand why this happened?
Code
MainActivity.java

public class MainActivity extends Activity {

public static TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.lolll);
    tv.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            startActivity(new Intent(MainActivity.this, MonActivity.class));
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

MonActivity.java - activity #2

public class MonActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mon);
    LayoutInflater inf = getLayoutInflater();
    RelativeLayout rel = (RelativeLayout) inf.inflate(R.layout.activity_main, null);
    TextView tv = (TextView) rel.findViewById(R.id.lolll);
    tv.setText("finger crossed");
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.mon, menu);
    return true;
}

}

4

1 回答 1

1

您不能(您可以通过静态视图定义来做到这一点,但不应该这样做!)直接从另一个活动更改活动的视图值/属性。使用 startActivityForResult 并传递并获取您的更改/新值 onActivityResult 方法。

我不会在这里分享任何示例或链接。您可以找到很多示例,只需搜索 startActivityForResult;)

编辑:如果您在活动中扩展布局,它会创建一个新的视图实例。因此,您对膨胀布局的更改将仅应用于该实例。

希望我的评论对你有所帮助。

于 2013-10-20T13:48:41.387 回答