layoutinflaterde 使用

  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值