layoutinflaterde 使用

来源:互联网 发布:linux怎么保存vim文件 编辑:程序博客网 时间:2024/05/11 21:38
  layoutinflaterde这个类感觉类似与findViewById()这个方法,但它不是寻找XML布局中的具体控件,而是寻找layout下的XML布局。在自定义View或者其他时候我们需要手动的加载布局文件,这时我们局需要用到layoutinflaterde获得layoutinflaterde的三种方法:
 LayoutInflater inflater = getLayoutInflater(); LayoutInflater inflater = LayoutInflater.from(context);   LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);

当然最常用的就是LayoutInflater inflater = LayoutInflater.from(context);
得到实例后,就可以加载布局了:
inflater.inflate(resourceId, root, boolean);
这里的三个参数
resourceId:需要加载布局的ID;
root:指给该布局的外部再嵌套一层父布局,如果不需要就直接传null,一般情况下传你的父布局;
boolean:如果你的root传null,则这里就不再有用,当root传入父布局时,这里就要设为false,否者你会发现你父布局的view都不见了。
下面举个例子:
在这里我们建一个空白的布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent"></LinearLayout>

再定义一个按钮

<Button xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:text="展示按钮" >  </Button> 

将按钮加载到空白布局中

public class MainActivity extends Activity {      private LinearLayout myLayout;      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          myLayout= (LinearLayout) findViewById(R.id.main_layout);          LayoutInflater layoutInflater = LayoutInflater.from(this);          View buttonLayout = layoutInflater.inflate(R.layout.button_layout, null);          mainLayout.addView(buttonLayout);      }  }  

OVER

0 0