跟 .NET 一样,安卓控件开发也分两种,一种是利用现有控件进行组合,扩展些方法、属性,免去调用,另一种就是什么都自己写。
首先、讲如何创建
我们假设要创建一个带文字的 Loading 效果的控件。我们右键,新建的时候,可以选择 UI Component -> Custom View。然后会生成三个文件:
1、位于 layout 下的布局文件<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
2、位于 values 下的属性配置文件
如下,只有第一个是我们个人写的,后面要用,后面几个属性是它默认的,我没删它。
3、就是 .java 文件了
java 文件,默认是继承自 View,我给改一下,继承自 RelativeLayout。然后改了下代码如下:package com.cqyuntong.components;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.cqyuntong.R;
import java.util.zip.Inflater;
public class Loading extends RelativeLayout {
public Loading(Context context, AttributeSet attrs) {
super(context, attrs);
View view = LayoutInflater.from(context).inflate(R.layout.component_loading, this, true); // 注意后面两个参数,表现要把布局文件加载给 this。
String text = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "text");
((TextView)view.findViewById(R.id.textView)).setText(text);
}
public void show() {
setVisibility(VISIBLE);
}
public void hide() {
setVisibility(GONE);
}
}
可以看出,在构造函数中,读取了属性 text 值,并将它赋给 TextView。然后我们自己搞了两个方法:show()、hide()。
控件就做好了。
熟练之后,我们也可以分开建了,第一步建一个布局文件,第二步建一个继承于某个控件(比如 LinearLayout)类,再将布局文件加载进来。而关于那个属性文件,大多数我们是不需要的。
还有一种情况,更简单,布局文件都不要,只要继承于某个控件的类,这多用于对该控件进行扩展,比如 ImageView 不支持网络图片,我们 extends 一个 NetImageView 类出来,人工添加加载网络图片的方法,然后我们在布局文件中直接使用 NetImageView。
下面,介绍下应用。
1、在布局文件中引用这个控件
android:id="@+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="加载中">
可以看出,有个 text 属性,就是我们前面介绍的。
2、在 .java 文件中使用这个控件((Loading)findViewById(R.id.loading)).show();
((Loading)findViewById(R.id.loading)).hide();
不多,介绍大家都懂。这样一个控件就完成了。
相关阅读