很多时候android常用的控件不能满足我们的需求,那么我们就需要自定义一个控件了。今天做了一个自定义控件的实例,来分享下。
首先定义一个layout实现按钮内部布局:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/buyfood_btn_reduce"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/dingcan_item_buy_left_bg"/>
<TextView
android:id="@+id/buyfood_txt"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/dingcan_item_buy_center"
android:gravity="center"
android:text="0"
android:textSize="20dp"
android:textStyle="bold"
/>
<Button
android:id="@+id/buyfood_btn_add"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/dingcan_item_buy_right_bg" />
</LinearLayout>
接下来写一个类继承LinearLayout,导入刚刚的布局,并且设置需要的方法,从而使的能在代码中控制这个自定义控件内容的显示。
package com.example.viewdemo;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* @author 作者 : 紫炎光
* @version 创建时间:2012-11-21 上午11:24:25
* 类说明
*/
public class DiyView extends LinearLayout {
private Button btn_add;
private Button btn_reduce;
private TextView tv;
public DiyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
Log.d("Infor", "来了哈1");
init();
}
public DiyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
Log.d("Infor", "来了哈2");
init();
}
private void init(){
LayoutInflater mLayoutInflater=
(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayoutInflater.inflate(R.layout.buyfood_item, this);
btn_add=(Button)this.findViewById(R.id.buyfood_btn_add);
btn_reduce=(Button)this.findViewById(R.id.buyfood_btn_reduce);
tv=(TextView)this.findViewById(R.id.buyfood_txt);
Log.d("Infor", "来了哈3");
// int totalWidth=((WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth();
}
public String getFoodSum(){
return tv.getText().toString();
}
}
在需要使用这个自定义控件的layout中加入这控件,只需要在xml中加入即可。
<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" >
<com.example.viewdemo.DiyView
android:id="@+id/abc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></com.example.viewdemo.DiyView>
</RelativeLayout>
PS:有的时候可能在XML中写入自定义控件时候,会报错:android.view.InflateException: Binary XML file line #7: Error inflating class com.example.viewdemo
查阅了一下原因。是因为自定义控件DiyView中缺少某构造函数。
public DiyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}
补齐这个构造器,异常就消失了。