Android控件的基本介绍及使用自定义控件的意义
Android 本身提供了很多控件, 自定义控件在android中被广泛运用,自定义控件给了我们很大的方便。比如说,一个视图为imageview ,imagebutton ,textview 等诸多控件的组合,用的地方有很多,我们不可能每次都来写3个的组合,既浪费时间,效率又低。在这种情况下,我们就可以自定义一个view来替换他们,不仅提升了效率并且在xml中运用也是相当的美观。
属性文件中format可选项
自定义控件就需要首先自定义该控件的属性。在开始前,我们需要检查在values目录下是否有attrs.xml,如果没有则创建。下面我们先来了解一下format属性类型都有哪些。
format可选项
l"reference" //引用
l"color" //颜色
l "boolean" //布尔值
l "dimension" //尺寸值
l "float" //浮点值
l "integer" //整型值
l "string" //字符串
l "fraction" //百分数 比如200%
我们可以在已有的控件的基础上,通过重写相关方法来实现我们的需求。 举一个最简单的例子说明,比如现在的RadioButton按钮只能存在一个text,如果我们想存储key-value对应的键值对,那么我们就需要自定义一个控件。这时定义的控件仅仅比RadioButton多了一个存储key的控件。实现如下:首先在开始前,我们需要检查在values目录下是否有attrs.xml,如果没有则创建。下面把创建的代码贴出来,如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RadioButton"><!-- 控件名称-->
<attr name="value" format="string"/><!-- 属性名称,类型-->
</declare-styleable>
</resources>
然后在创建MRadioButton类,该类继承RadioButton。代码如下:
public class MyRadioButton extends android.widget.RadioButton implements OnCheckedChangeListener {
private String mValue;
public MyRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
try {
/**
* 跟values/attrs.xml里面定义的属性绑定
*/
//TypedArray其实就是一个存放资源的Array
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.RadioButton);
this.mValue = a.getString(R.styleable.RadioButton_value);
//重复使用对象的styleable属性
a.recycle();
} catch (Exception e) {
e.printStackTrace();
}
setOnCheckedChangeListener(this);
}
public String getValue() {
return this.mValue;
}
public void setValue(String value) {
this.mValue = value;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println( "-------Main te new value is ===>" + this.getValue());
}
}
然后再看Layout中的xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fsms="http://schemas.android.com/apk/res/com.cherry.myview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.cherry.view.MyRadioButton
android:id="@+id/isPayDepositTrue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/yes"
android:textSize="18sp"
fsms:value="true" >
</com.cherry.view.MyRadioButton>
</LinearLayout>
其中:xmlns:fsms=http://schemas.android.com/apk/res/com.cherry.myview为定义命名空间路径,这里定义完后,就可以对value进行赋值了。
最后我们来看一下Main函数:
public class MyView extends Activity {
private MyRadioButton isPayDepositTrue;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
isPayDepositTrue = (MyRadioButton) findViewById(R.id.isPayDepositTrue);
//isPayDepositTrue.setValue("false");
isPayDepositTrue.setChecked(Boolean.valueOf(isPayDepositTrue.getValue()));
}
}
编译运行,效果如下: