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
原创粉丝点击