本文共 2387 字,大约阅读时间需要 7 分钟。
当使用简单布局定义界面时,客户端对手机内存的消耗是巨大的,同时过多的布局嵌套让代码显得异常的凌乱。因此,解决方式就是自定义控件。接下来,一步一步来实现自定义界面。
(1)自定义View的属性
(2)在View的构造方法中获得我们自定义的属性 (3)重写onMesure (不是必须的) (4)重写onDraw (5)在布局中使用此自定义View(1)自定义布局(基础)
(2)自定义布局对应的属性(attr.xml) (3)在View的构造方法中获得“自定义布局的控件”&“自定义的属性”(attr.xml),将attr.xml取得的属性值添加到自定义的控件中绑定。 (4)重写onMesure (不是必须的) (5)重写onDraw (6)在布局中使用此自定义View##3 例子代码讲解
###3.1 attrs.xml/** * Created by Guan on 2015/7/25. */public class MyView extends FrameLayout { private ImageView mMoreImage; private TextView mCustomer; private ImageView mRightImage; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); // 1.1 通过布局view_custom.xml自定义每一行的格式 // 1.2 再获取到view,并获取到具体的控件 View view = View.inflate(context, R.layout.view_coutom, this); mMoreImage = (ImageView) view.findViewById(R.id.iv_more); mCustomer = (TextView) view.findViewById(R.id.tv_customer); mRightImage = (ImageView) view.findViewById(R.id.iv_right); // 2.1 通过布局attr.xml自定义每一行View的属性 // 2.2 通过attr.xml取得declare-styleable集合,从集合里取出相对应的属性值 TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.zView); Drawable imageMore = typeArray.getDrawable(R.styleable.zView_iconMore); String customerString = typeArray.getString(R.styleable.zView_textCustomer); Drawable imageRight = typeArray.getDrawable(R.styleable.zView_iconRight); // 3.将attr.xml取得的属性值添加到自定义的控件中绑定 mMoreImage.setImageDrawable(imageMore); mCustomer.setText(customerString); mRightImage.setImageDrawable(imageRight); // 关闭资源 typeArray.recycle(); } // 4.重写onDraw @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); }}
在XML使用该组件的时候一定要为该自定义组件设置一个命名空间。
命名空间写法:xmlns:空间名="http://schemas.android.com/apk/res/自定义组件所在包名"
命名空间写法:xmlns:空间名="http://schemas.android.com/apk/res-auto"
例如:xmlns:myandroid="http://schemas.android.com/apk/res-auto"转载地址:http://vmcub.baihongyu.com/