自定义布局控件
2015-11-07 17:14
357 查看
本文介绍一种自定义控件的方法,由控件布局和控件代码2部分组成。效果为一个自定义标题栏,由一个按钮、一个文本、一个按钮组成,并定义了各子件的事件。
一、title布局如下
二、代码如下。重写构造器,在其中展开布局,找到子控件绑定事件
三、活动中引入自定义控件,要使用完整包名
<com.ui.TitleLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
四、自定义控件也可以在主活动中重新定义子控件的属性及事件
一、title布局如下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/title_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dip" android:text="Back" android:textColor="#fff" /> <TextView android:id="@+id/title_text" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:gravity="center" android:text="Title Text" android:textColor="#fff" android:textSize="24sp" /> <Button android:id="@+id/title_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dip" android:text="Edit" android:textColor="#fff" /> </LinearLayout>
二、代码如下。重写构造器,在其中展开布局,找到子控件绑定事件
public class TitleLayout extends LinearLayout { public TitleLayout(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.title, this); Button titleBack = (Button) findViewById(R.id.title_back); Button titleEdit = (Button) findViewById(R.id.title_edit); titleBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ((Activity) getContext()).finish(); } }); titleEdit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(), "You clicked Edit button", Toast.LENGTH_SHORT).show(); } }); } }
三、活动中引入自定义控件,要使用完整包名
<com.ui.TitleLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
四、自定义控件也可以在主活动中重新定义子控件的属性及事件
相关文章推荐
- [深入理解Java虚拟机]第十二章 Java内存模型与线程-Java内存模型
- C++异步调用Future机制漫谈
- java注释
- ios新手如何看xcode缓存路径
- Amazon S3数据一致性模型
- 第五次课后实验
- python之函数用法execfile()
- lintcode 中等题:Submatrix sum is 0 和为零的子矩阵
- 约瑟夫环
- Retrofit2.0.0-beta2简单使用
- 汉诺塔问题
- Matlab的unique函数的C++实现
- hdu5532Almost Sorted Array 最长递增子序列模板水题
- 人总有些东西需要一直坚守
- EditText特定字符的输入与校验
- 欢迎使用CSDN-markdown编辑器
- UVA 11235 Frequent values
- 利用WinPcap模拟网络包伪造飞秋闪屏报文
- 斯坦福大学-机器学习20讲-第二讲
- POJ3764:The xor-longest Path