安卓自定义控件全解

全栈工程师开发手册 (作者:栾鹏)

安卓教程全解

安卓自定义控件:包含LinearLayout、RelativeLayout、GridView、Button等

本文以LinearLayout为例

首先要有一个自定义xml布局文件

我们这里存储下面的代码为ui_linearlayout.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">
  <EditText
    android:id="@+id/ui_linearlayout_editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="4"
  />
  <Button
    android:id="@+id/ui_linearlayout_clearButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="搜索"
    android:layout_weight="1"
  />
</LinearLayout>

自定义控件继承自LinearLayout

在自定义控件的绑定布局文件,并进行相应的ui初始化,添加自定义的属性和方法。

//自定义组合控件
public class UI_LinearLayout extends LinearLayout{  
	  private View view;
	  private LayoutInflater layoutInflater;
	  private EditText editText;
	  private Button clearButton;
	  
	  public UI_LinearLayout(Context context) {   //自己定义构造函数,可以传递想要的数据进来
	    super(context);

	    //使用布局资源填充视图
	    String infService = Context.LAYOUT_INFLATER_SERVICE;
	    layoutInflater = (LayoutInflater)getContext().getSystemService(infService);  //layoutInflater=LayoutInflater.from(context);
	    view = layoutInflater.inflate(R.layout.ui_linearlayout, this, true);   //获取当前控件的引用,使用this也行
	    //获取对子控件的引用
	    editText = (EditText)findViewById(R.id.ui_linearlayout_editText);
	    clearButton = (Button)findViewById(R.id.ui_linearlayout_clearButton);
	    //也可以使用代码自己添加
	  }
	 
	//组合控件的自定义函数
	private void fun1(String str,Drawable Images,OnClickListener onclick){
		editText.setText(str);
		clearButton.setBackgroundDrawable(Images);
		clearButton.setOnClickListener(onclick);
	}

在activity中添加自定义控件

RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.activity1_relativeLayout1);
UI_LinearLayout myview = new UI_LinearLayout(this);
relativeLayout .addView(myview);
//myview.fun1(str, Images, onclick);   //调用内部函数

在窗口ui布局的xml中添加自定义控件

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

腾讯AI架构师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值