自定义控件

    xiaoxiao2025-01-18  12

    编写布局xml文件  ,假设已经编好一个名为title.xml的布局文件。

    则可以在其它xml布局文件中使用include语句引用该布局:

    <include layout="@layout/title"/>这样可以解决重复编写布局代码的问题,但是如果布局中有一些控件要求能够响应事件,且该控件响应的事件都是一样的,比如返回键,这种情况最好使用自定义控件的方式来解决:

    ①编写xml布局文件  。

    ②新建类继承布局类 ,并在类中加载布局,为控件注册事件。

    public class TitleLayout extends LinearLayout { public TitleLayout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub LayoutInflater.from(context).inflate(R.layout.title, this);//加载布局 Button titlebackButton =(Button) findViewById(R.id.title_back); Button titleeditButton =(Button) findViewById(R.id.title_edit); titlebackButton.setOnClickListener(new OnClickListener() {//为控件添加事件 @Override public void onClick(View arg0) { // TODO Auto-generated method stub ((Activity)getContext()).finish(); } }); titleeditButton.setOnClickListener(new OnClickListener() {//为控件添加事件 @Override public void onClick(View arg0) { // TODO Auto-generated method stub Toast.makeText(getContext(), "you clicked edit button", Toast.LENGTH_SHORT).show(); } }); } }③在xml文件中引入布局

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.uicustomviews.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content" > </com.example.uicustomviews.TitleLayout> </LinearLayout> 这里需要指明控件的完整类名

    转载请注明原文地址: https://ju.6miu.com/read-1295613.html
    最新回复(0)