Reputation: 119
I have seen many answers here but I couldn't actually understand what it is and why is it used.
Can someone give a little easy description to understand it? Thanks a lot
Upvotes: 2
Views: 12479
Reputation: 2864
LayoutInflater is used to manipulate Android screen using predefined XML layouts. this class is used to instantiate layout XML file into its corresponding View objects. It is never used directly. Instead, use getLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context.
Simple Program for LayoutInflater- make this layout as your activity_main.xml-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</LinearLayout>
this is the hidden layout which we will add dynamically,save it as hidden_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hidden_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, this is the inflated text of hidden layout"/>
<EditText android:id="@+id/edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, this is your name"/>
</LineraLayout>
Now this is the code for main activity-
public class MainActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout main = (LinearLayout)findViewById(R.id.main_layout);
View view = getLayoutInflater().inflate(R.layout.hidden_layout, main,false);
main.addView(view);
}
}
note-We use the "false"attribute because this way any further layout changes we make to the loaded view,will take effect. If we have set it to "true" it would return the root object again, which would prevent further layout changes to the loaded object.
Upvotes: 6
Reputation: 436
Basically it is needed to create (or fill) View based on XML file in runtime. For example if you need to generate views dynamically for your ListView items and that's all about it.
Upvotes: 7