开发经常会用到自定义布局容器,总结一下自定义LinearLayout的几种方式:
第一种:
步骤:
1.自定义布局类,继承LinearLayout,如:创建CustomLinearLayout类,注意添加必要的构造方法以及重写View的 onFinishInflate()方法
2.在XML布局文件中布局好所有子元素
3.在CustomLinearLayout中声明与XML布局文件中所有子元素对应的引用,并在onFinishInflate()方法中通过 findViewById()方法将所有引用跟XML布局文件中声明的视图组件匹配起来,这样就可以通过CustomLinearLayout类中声明的引用来操作XML布局中声明的视图组件了.
如:CustomLinearLayout.java类文件
public class CustomLinearLayout extends LinearLayout
{
private TextView textView = null;
private ListView listView = null;
public CustomLinearLayout(Context context)
{
super(context);
Log.i("CustomLinearLayout(Context context)");
}
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i("CustomLinearLayout(Context context, AttributeSet attrs)");
Log.i("attrs.getAttributeCount()="+ attrs.getAttributeCount());
for(int i=0;i<attrs.getAttributeCount();i++)
Log.i("attribute["+i+"]="+attrs.getAttributeName(i));
}
public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Log.i("CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr)");
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
Log.i("onFinishInflate()");
textView = (TextView)findViewById(R.id.textView);
textView.setText("我是自定义控件中的一个TextView");
listView =(ListView) findViewById(R.id.listview);
listView.setCacheColorHint(0);
listView.setDivider(null);
listView.setBackgroundColor(0x0000ff);
}
}
linearlayout_custom.xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<com.yzp.customlinearlayout.CustomLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/customLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
style="@style/AppTheme">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是自定义布局的第一个Textview"/>
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</com.yzp.customlinearlayout.CustomLinearLayout>
这样就可以使用了,如在activity_main.xml文件中使用:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.yzp.customlinearlayout.MainActivity" >
<include layout="@layout/linearlayout_custom"/>"
</RelativeLayout>
另外,关于自定义View的构造方法中的第三个参数defStyle的意义的可以看这篇文章:http://www.cnblogs.com/angeldevil/p/3479431.html