Android学习(8)-自定义组件
来源:互联网 发布:淘宝2016创业成功案例 编辑:程序博客网 时间:2024/06/06 04:47
控件和布局之间关系如果所示:
view
----TextView
----EditText
----Button
----ImageView
----ViewGroup
----LinerLayout
----RelativeLayout
(1) 如果很多界面用同一部分的界面,可以在布局中引入该界面。
如创建一个title.xml的layout,那么在其他界面中使用这个界面的时候只需要在layout.xml中通过<include layout="@layout/title">便可以引入界面。
(2)上述问题解决了重复编写布局代码的问题。但是如果每个活动中都有一个按钮,功能相同,那么如果在每一个活动中都写一次这个按钮的响应,那就非常繁琐。这种情况最好使用自定义组件来解决。如,我们如果定义一个组件:
即在每一个活动中都可以直接用到这个符合组件,而且返回和编辑点击后都有响应事件。
首先代码实现一个组件:
public class TitleLayout extends LinearLayout {//继承LinearLayoutpublic TitleLayout(Context context, AttributeSet attrs) {//重写带有两个参数的构造函数super(context, attrs);LayoutInflater.from(context).inflate(R.layout.title, this);//在布局中引入TitleLayout控件的时候就会用到调用构造函数。实现动态加载就调用LayoutInflater的from方法来创建一个LayoutInflater对象,通过inflater就可以动态加载一个布局文件//inflate方法的两个参数,第一个参数是加载布局文件的id,第二个是为加载好的布局添加一个父布局Button backButton = (Button)findViewById(R.id.button2);Button editButton = (Button)findViewById(R.id.button1);backButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub((Activity)getContext()).finish();}});}}在layout中使用该组件的方法:
<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=".MainActivity" > <com.example.uicustomviews.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content" ></com.example.uicustomviews.TitleLayout></RelativeLayout>
0 0
- Android学习(8)-自定义组件
- Android 自定义组件学习 2
- Android 自定义组件学习 3
- Android学习—自定义组件
- Android学习—自定义组件
- Android学习笔记:(一)添加自定义组件(slideMenu)
- Android自定义组件学习笔记(1)---仿网页进度条
- Android学习笔记之自定义UI组件
- Android自定义组件(一)
- Android自定义组件(二)
- 【Android】Android自定义组件
- 2014-11-8Android学习------深入理解Android中ViewGroup-----自定义组件
- JSF学习 自定义组件(转)
- 自定义组件 学习
- Android自定义组件(一)(二)
- Android组件 自定义下拉菜单(Spinner)
- android 自定义组件(declare-styleable)
- android中自定义组合组件(一)
- php设计模式——策略模式
- C罗,一个关于坚持的故事
- MFC CToolBar使用总结
- hadoop 测试环境搭建
- 深入理解HashMap(及hash函数的真正巧妙之处)
- Android学习(8)-自定义组件
- 模取幂
- java.util.concurrent.locks与synchronized及其异同
- javascript性能优化小知识
- Fedora上安装并配置samba服务
- 解决一加手机没有移动3G信号
- 什么是嵌入式系统
- iOS 小技巧
- LeetCode:Two Sum