Android学习(8)-自定义组件

本文探讨了在Android开发中如何利用自定义组件和布局复用解决代码冗余问题,通过实例展示了如何创建和使用组件,以及在不同布局中引入已有布局的方法,有效提高了开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 控件和布局之间关系如果所示:

view

----TextView

----EditText

----Button

----ImageView

----ViewGroup

----LinerLayout

----RelativeLayout

(1) 如果很多界面用同一部分的界面,可以在布局中引入该界面。

如创建一个title.xml的layout,那么在其他界面中使用这个界面的时候只需要在layout.xml中通过<include layout="@layout/title">便可以引入界面。

(2)上述问题解决了重复编写布局代码的问题。但是如果每个活动中都有一个按钮,功能相同,那么如果在每一个活动中都写一次这个按钮的响应,那就非常繁琐。这种情况最好使用自定义组件来解决。如,我们如果定义一个组件:


即在每一个活动中都可以直接用到这个符合组件,而且返回和编辑点击后都有响应事件。

首先代码实现一个组件:

public class TitleLayout extends LinearLayout {
//继承LinearLayout


public 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() {

@Override
public 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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值