Android include标签遇到的坑

1.include标签在activity.xml使用如下:

<include
    layout="@layout/page_blank"
/>
 
 

2.include标签在所对应的layout布局使用如下:

 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:id="@+id/rl_blank"
    android:clickable="true"
    android:visibility="gone"
    android:layout_height="match_parent">
    <!--<Button-->
    <!--android:id="@+id/btn_click_me"-->
    <!--android:layout_width="100dp"-->
    <!--android:layout_height="100dp" />-->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@mipmap/blank" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="什么也没找到呀~~"
            android:layout_marginTop="@dimen/x14" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="请点击页面,重新刷新~~"
            android:layout_marginTop="@dimen/x14" />

    </LinearLayout>
 

注意1.在activity中如果include标签没有id,则include标签内所包含的子View可以直接通过findViewById找到如果include标签有id,那么必须findViewById(include的id).findViewById(子view的id)或者通过布局填充器,View view = LayoutInflate.from(context).inflate(include 的布局,null);view.findViewById获取子view

 

注意2.如果include布局中想对子view,Button进行点击事件并且include标签有id,那么

Button btn = (Button)findViewById(include的id).findViewById(子view的id);

btn.setOnclickListner();这种 方式可以

View view = LayoutInflate.from(context).inflate(include 的布局,null);

Button btn = (Button)view.findViewById(子view的id);

btn.setOnclickListner();这种 方式不可以,点击是事件不响应

注意3.如果include布局中想对子view,LinearLayout进行点击事件并且include标签有id,那么

 

 

LinearLayout ly = (LinearLayout )findViewById(include的id).findViewById(子view的id);

ly .setOnclickListner();这种 方式不可以,点击事件不响应

 

 

 

View view = LayoutInflate.from(context).inflate(include 的布局,null);

LinearLayout ly = (LinearLayout )view.findViewById(子view的id);

这种方式直接出错,空指针,找不到该控件

 

所以想对include内部的子view做点击事件,最好是不要在include标签中添加id

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值