小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Android include 標(biāo)簽

 Babylly 2011-12-08
android中include標(biāo)簽是為了便于控件的覆用的一個(gè)很好解決方案。

但是也有一些需要注意的地方,下面是本人在項(xiàng)目中碰到過的一個(gè)問題,做此記錄,便于以后查看。

include標(biāo)簽用法。

1.新建一個(gè)xml文件,命名 head.xml
head.xml文件內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas./apk/res/android"
                android:id="@+id/index_linear_foot"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
        <ImageView
            android:id="@+id/head_btn_refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        />
</RelativeLayout>
2.新建一個(gè)布局文件,命名 main.xml
main.xml文件內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas./apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
>
<include android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/head" />
</LinearLayout>
注意:上面我們的include標(biāo)簽中是沒有為它指定id的。

3.新建一個(gè)MainActivity,設(shè)置布局文件為main.xml;

4.假設(shè)我現(xiàn)在需要在代碼中為head.xml中的RelativeLayout容器設(shè)置背景圖片。
代碼如下:
//獲得布局容器對(duì)象
RelativeLayout head = (RelativeLayout)findViewById(R.id.index_linear_foot);
//設(shè)置背景圖片
head.setBackgroundResource(R.drawable.head);
這樣就OK了。

5.剛剛說到,我們的include標(biāo)簽中是沒有為它指定id的,假設(shè)我們現(xiàn)在的main.xml文件布局容器是RelativeLayout,而我需要把某個(gè)控件放在head.xml下面。就需要使用到RelativeLayout布局容器的特有屬性 android:layout_below="" 屬性。還需要為include指定id屬性。
那我們的main.xml文件變成如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas./apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<include android:id="@+id/main_head" android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/head" />
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/main_headb"
/>
</RelativeLayout>
那接下來我們?cè)谶\(yùn)行我們的實(shí)例,結(jié)果發(fā)現(xiàn),代碼在運(yùn)行到head.setBackgroundResource(R.drawable.head);
這一句的時(shí)候拋異常了
java.lang.NullPointerException

原來:如果include指定了id的話,就不能直接把它里面的控件當(dāng)成主xml中的控件來直接獲得了,必須先獲得這個(gè)xml布局文件,再通過布局文件findViewById來獲得其子控件。
代碼如下
View layout = getLayoutInflater().inflate(R.layout.head, null);
RelativeLayout head= (RelativeLayout)layout.findViewById(R.id.index_linear_foot);
//設(shè)置背景圖片
head.setBackgroundResource(R.drawable.head);
這樣就可以了。

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多