View
实例化
流程(高级)
小智
原理:View通过LayoutInflater实现加载
我们一般讲的先把View实例化成对象通过3种方式去实现:
1.LayoutInflater layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(resourceId, root);
2.LayoutInflater layoutInflater=LayoutInflater.from(context);
layoutInflater.inflate(resourceId, root);
3.View view=View.inflater(context,resourceId, root);
这三种方式的作用都是一样的,第二种其实是对第一种的封装,第三种是对第二种的封装。
使用:
我们一般都是使用这种方式去拿到一个布局,然后添加到另一个布局上面,步骤也很简单。我们来看一下以下代码。
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
view.xml
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" >
</Button>
MainActivity java代码
public class MainActivity extends Activity {