【Android-布局復用】 多個界面復用一個布局文件(二)


多個界面復用一個布局界面 ,如何找到復用布局文件中的控件的id?

 

舉個栗子:

1.  layout_common.xml  

復用的布局文件,如何找到button 的id?

<?xml version="1.0" encoding="utf-8"?>
<!-- 復用的布局文件 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/common_button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按鈕1" />

</LinearLayout>

2.layout_main.xml

關鍵是給include的布局添加一個id

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

    <!-- 在布局文件中引用復用的布局文件 -->

    <include
        android:id="@+id/common_layout"
        layout="@layout/layout_common" />

</LinearLayout>
 

3.MainActivity.java

然后就可以通過以下代碼找到 復用布局文件控件的id了。

View view=findViewById(R.id.common_layout);
Button button=view.findViewById(R.id.common_button1);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM