在Android开发中,常用的组件有时候无法满足我们的需求,因此我们需要自定义组件,这样可以提高组件的复用性,通过继承已有的组件,在此基础上对塔改进,下面演示简单一个一个按钮控件,塔包含2个ImageView和1个TextView。
1.组件模板
mybutton.xml
17 15 23 31
2.继承父组件
MyButton.java
1 public class MyButton extends LinearLayout{ 2 3 private ImageView imgaeView; //图标 4 private TextView textView; //文字 5 private ImageView arrow; //箭头 6 public MyButton(Context context) { 7 super(context); 8 9 }10 public MyButton(Context context, AttributeSet attrs) {11 super(context, attrs);12 initView(context);13 }14 private void initView(Context context){15 LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);16 LinearLayout linearLayout=(LinearLayout) inflater.inflate(R.layout.mybutton, this);17 imgaeView=(ImageView)linearLayout.findViewById(R.id.icon);18 textView=(TextView) linearLayout.findViewById(R.id.text);19 arrow=(ImageView) linearLayout.findViewById(R.id.arrow);20 }21 //修改icon 22 public void setImageViewResource(int resId){23 imgaeView.setImageResource(resId);24 }25 //修改文本26 public void setTextViewText(String text){27 textView.setText(text);28 }29 30 31 32 }
3.Layout添加组件
4.定义背景
bg.xml
12 - 3
- 4
bg1.xml
12 3
bg2.xml
12 3