johntheripp3r
johntheripp3r

Reputation: 989

Inflating Layout and changing value of textview

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;
}

}

Upvotes: 1

Views: 1641

Answers (1)

Devrim
Devrim

Reputation: 15533

You can not (you can do this by static view definition but should not do it!) change an activity's value/property of view directly from another activity. Use startActivityForResult and pass and get your changed/new value onActivityResult method.

I'm not sharing any example or link here. You can find many samples, just search startActivityForResult;)

Edit: if you inflate a layout at an activity, it creates a new instance of a view. So your changes on the inflated layout will only applied to that instance.

I hope my comment helps you.

Upvotes: 1

Related Questions