如何自定义LinearLayout

喜欢而已 提交于 2019-12-05 13:09:05

最近通过看别人代码和网上搜索,发现现在自定义LinearLayout的方式有两种。第一种是在扩展的LinearLayout构造函数中使用Inflater加载一个布局,并从中提取出相关的UI组件进行封装,形成一个独立的控件。在使用该控件时,由于它所有的子元素都是在运行时通过代码动态创建的,所以该控件只能以一个独立控件的形式在Layout文件中声明,例如:

<com.XX.CustomLayout android:id="@+id/XX"

        android:layout_width="XX"

        android:layout_height="YY" />

另一种使用方式是:在自定义控件中声明它的所有子元素,然后在Layout文件中像使用LinearLayout一样去进行布局,不过切记:自定义控件Code中声明的UI元素必须与Layout文件中声明的元素保持一致,否则,在代码中无法找到对应的控件;最后,在自定义控件的onInflateFinish中通过findViewById将layout中声明的控件跟代码中声明的控件匹配起来,例如有某个自定义控件:

public class CustomLayout extends LinearLayout{
    ListView  mListView; //代码中声明的控件

    XXXX; //针对UI控件封装的操作

}

Layout文件中使用该布局进行声明:

<com.XX.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
        <ListView android:layout_width="wrap_content"  
          android:layout_height="fill_parent"  
          android:id="@+id/ListView01" 
          />
</com.XX.CustomLayout>

最后在代码中进行匹配:

protected void onFinishInflate()  
    {               
        mListView=(ListView)findViewById(R.id.ListView01);   
        mListView.setAdapter(mAdapter);
        mListView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        mListView.setBackgroundColor(0xF3EEE5);
        mListView.setCacheColorHint(0);
        mListView.setDivider(null);
           
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!