Android:LayoutInflater载入没有载入或想动态载入的layout

    当一个Activity想要调用多个layout中的控件,就可以通过LayoutInflate getSystemService方法载入该控件所在的layout,

  下面以一个TextView为例,具体代码如下:

1.activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/activity"
    tools:context=".Activity" >

    <TextView
        android:id="@+id/mTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView" />

</RelativeLayout>

2. Activity中调用该layout的方法,代码如下

private ViewGroup show;
private View layout;
LayoutInflater inflater
= (LayoutInflater) this.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); show= (ViewGroup)findViewById(R.id.activity); layout= inflater.inflate(R.layout.activity,show); mTextView= (TextView) layout.findViewById(R.id.mTextView); setContentView(layout); //这句话很重要,是实时显示该界面的方法

注:当出现界面按钮无反应等,由于界面没有实时更新造成的问题,可检查是否是setContentView(layout);没有写对。

原文地址:https://www.cnblogs.com/Bubls/p/4503503.html