I don't fully understand LayoutInflater functions though I used it in my projects. For me it's just a way to find view when I cannot call findViewById method. But sometimes it does not work like I expect.
I have this really simple layout (main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/layout">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
android:id="@+id/txt"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change text"
android:id="@+id/btn"/>
</LinearLayout>
What I want is very simple - just to change text inside TextView when pressing the button. Everything works fine like this
public class MyActivity extends Activity implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
TextView txt = (TextView) findViewById(R.id.txt);
double random = Math.random();
txt.setText(String.valueOf(random));
}
}
But I want to understand what would be the equivalent using LayoutInflater? I tried this, but without success, TextView didn't change its value
@Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View main = inflater.inflate(R.layout.main, null);
TextView txt = (TextView) main.findViewById(R.id.txt);
double random = Math.random();
txt.setText(String.valueOf(random));
}
But when debugging I can see that each variable populates with right value. I mean txt variable actually contains TextView which value is "Hello World, MyActivity", and after setText method it contains some random number but I couldn't see this changes on UI. It's the main problem I faced with LayoutInflater in my projects - for some reason I can't update inflated views. Why?