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?
That is incorrect. The
LayoutInflateris used to inflate(build) a view hierarchy from the provided xml layout file. With your second code snippet you build the view hierarchy from the layout file(R.layout.main), find theTextViewfrom that inflated view and set the text on it. The problem is that this inflated view isn’t attached to the visibile UI of theActivity. You could see the changes, for example, if you call againsetContentViewthis time giving it the inflated view. This will make the content of yourActivityto be the newly inflatedView: