何时在Android中使用LayoutInflater

Leo*_*s I 2 android

我在这里看到了许多答案但我实际上无法理解它是什么以及为什么使用它.

有人能给出一点简单的描述来理解它吗?非常感谢

Met*_*oiD 7

基本上,需要在运行时基于XML文件创建(或填充)View.例如,如果您需要为ListView项动态生成视图,那就是它的全部内容.


sky*_*ine 6

LayoutInflater用于使用预定义的XML布局操作Android屏幕.此类用于将布局XML文件实例化为其对应的View对象.它永远不会直接使用.相反,使用getLayoutInflater()或getSystemService(String)来检索已连接到当前上下文的标准LayoutInflater实例.

LayoutInflater的简单程序 - 将此布局设为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>
Run Code Online (Sandbox Code Playgroud)

现在这是主要活动的代码 -

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

}
}
Run Code Online (Sandbox Code Playgroud)

note - 我们使用"false"属性,因为这样我们对加载的视图进行的任何进一步布局更改都将生效.如果我们将其设置为"true",它将再次返回根对象,这将阻止对加载的对象进行进一步的布局更改.