Android 自定义控件初探

自定义控件与自定义属性在Android开发中的应用
本文介绍了如何在Android开发中创建自定义控件和使用自定义属性,通过继承View类并复写相关方法,实现自定义控件的基本功能。文章详细解释了自定义控件的构造方法、在布局文件中的使用方式,以及如何获取和应用自定义属性,最终展示了如何在Activity中获取并操作自定义控件。

Android为开发人员提供了一系列组件进行UI的设计。基于View和ViewGroup两个基类,由大量的原生组件供我们使用,包括ButtonTextViewEditViewListViewCheckBoxRadioButtonGallerySpiner 等组件以及 LinearayoutFrameLayoutRelativeLayout等布局。

在开发中,如果这些组件无法满足我们的需求,就要通过创建一个继承View的子类来实现自定义控件了。当然,如果只希望对已有的控件进行一些修改,也可以创建一个已有的控件的子类,对其方法进行重写。

下面就简单的实现一个自定义控件。


##创建一个类##

public class SettingView extends RelativeLayout {

	private TextView setting_view_tv;
	private ImageView setting_view_iv;

    //重写构造函数
    public SettingView(Context context) {
        super(context);
    }

    public SettingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.setting_view, this);

        setting_view_iv = (ImageView) view.findViewById(R.id.setting_view_iv);
        setting_view_tv = (TextView) view.findViewById(R.id.settin_view_tv);
    }

    public SettingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


	//自定义方法,给ImageView添加图片
	public void setImageRes(int resId){
		setting_view_iv.setImageResource(resId);
	}

	//自定义方法,给TextView添加文本
	public void setText(String content){
		setting_view_tv.setText(content);
	}
}
构造方法描述
View(Context context)Simple constructor to use when creating a view from code.
View(Context context, AttributeSet attrs)Constructor that is called when inflating a view from XML.
View(Context context, AttributeSet attrs, int defStyleAttr)Perform inflation from XML and apply a class-specific base style from a theme attribute.
View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)Perform inflation from XML and apply a class-specific base style from a theme attribute or style resource.

只要我们实现了第二个构造函数,就可以在.XML布局文件中使用该自定义的控件了。


##在布局文件中使用自定义控件##

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        style="@style/TitleTheme"
        android:text="Setting" />

    <com.example.dio.ui.SettingView
        android:id="@+id/settingview_demo1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <com.example.dio.ui.SettingView
        android:id="@+id/settingview_demo2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp" />

</LinearLayout>

通过使用全类名来在布局文件中加载自定义的控件。


##在Activity中获取控件##

在布局文件中加载完自定义的控件后,就可以在Activity.java文件中获取到这个控件并且调用其方法了。

public class SettingActivity extends Activity {

    
	@Bind(R.id.settingview_demo1)
    SettingView settingviewDemo1;
	@Bind(R.id.settingview_demo2)
    SettingView settingviewDemo2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        initView();
    }
	
	//初始化控件的内容
    private void initView() {
        settingviewDemo1.setImageRes(R.drawable.demo1);
		settingviewDemo1.setText("This is Consum View 1");

		settingviewDemo1.setImageRes(R.drawable.demo2);
		settingviewDemo1.setText("This is Consum View 2");
    }
}

在这里我使用了ButterKnife的注入方式获取了控件,并且在初始化控件内容时调用了其方法。

这样就完成了我们自定义控件的简单实现。


##自定义属性##

上面我们只是简单的实现了自定义控件。但是当我们在.XML布局文件中使用系统所提供的控件时,可以使用各种属性来控制控件在屏幕上的显示效果。而我们自定义的控件暂时只能使用从父类所继承的属性。

那么如何在自定义控件上使用我们自己所定义的属性呢。首先我们需要在/res/values/文件夹下创建一个attrs.xml文件。通过文件名也可以知道,这个.xml文件是我们用来定义属性的。

<resources>
    <declare-styleable name="SettingView">
        <attr name="text" format="string"/>

        <attr name="hasSwitch" format="boolean"/>

        <attr name="background" format="string">
            <enum name="first" value="0"/>
            <enum name="middle" value="1"/>
            <enum name="last" value="2"/>
        </attr>
    </declare-styleable>
</resources>

在attrs.xml文件中,我们先通过 <declare-styleable name="SettingView"></declare-styleable> 声明了自定义的属性集的名字。而 <attr name="text" format="string" />就是我们所定义的属性及其类型。


##在布局文件中使用自定义控件##

在我们自定义完属性之后,就可以在布局文件中使用了。但是这里还需要对布局文件进行一些修改。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:dio="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        style="@style/TitleTheme"
        android:text="Setting" />

    <com.example.dio.ui.SettingView
        android:id="@+id/setting_autoupdate_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        dio:settingformat="first"
        dio:text="This is Consum View 1" />

    <com.example.dio.ui.SettingView
        android:id="@+id/setting_antiharass_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        dio:settingformat="last"
        dio:settingtitle="This is Consum View 1" />

</LinearLayout>

首先,我们在布局文件中声明了xmlns:dio="http://schemas.android.com/apk/res-auto"。

这里的"dio"可以是任意的值,仅仅是我们在布局文件中调用的一个标识。而后面的url地址需要使用自定义控件的包名,表明使用自定义属性的是那种控件。

要注意的是,这里我使用的是xmlns:dio="http://schemas.android.com/apk/res-auto"而不是完整包名,这是Android Studio所提供的新语法,表示由程序自动匹配使用了自定义属性的控件。(可能不太准确,但是这是AS所提供的一种便利)


##获取自定义属性##

现在我们已经在自定义的控件中使用了自定义属性了,那么我们如何获取这些自定义属性,并且使控件做出相应的变化?

在自定义控件的.java文件中

public class SettingView extends RelativeLayout {

    private TextView setting_view_tv;
    private ImageView setting_view_iv;

    public SettingView(Context context) {
        super(context);
    }

    public SettingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //将布局文件挂载到自定义的View中
        View view = LayoutInflater.from(getContext()).inflate(R.layout.setting_view, this);
		
		setting_view_iv = (ImageView) view.findViewById(R.id.setting_view_iv);
        setting_view_tv = (TextView) view.findViewById(R.id.settin_view_tv);

        //获取自定义的属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SettingView);
        String text = typedArray.getString(R.styleable.SettingView_text);
        int background = typedArray.getInt(R.styleable.SettingView_background, 0);
        typedArray.recycle();//关闭资源

        //通过获取的属性,定义控件内容
        setting_view_tv.setText(title);
        
        switch (background) {
            case 0:
                view.setBackgroundResource(R.drawable.background1);
                break;
            case 1:
                view.setBackgroundResource(R.drawable.background2);
                break;
            case 2:
                view.setBackgroundResource(R.drawable.background3);
                break;
        }
    }

    public SettingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

在自定义控件的.java文件中,我们通过context.obtainStyledAtrributes()来获取自定义的属性,其中的两个属性分别表示我们定义属性的.xml文件名和其中的属性集名。这个方法返回的TypedArray是以键值对封装的自定义属性集合,在这个集合中我们就可以获取到之前所定义的属性,并通过属性来设置空间的内容了。


上面就是自定义控件和自定义属性的简单用法,但现在还只是通过继承一些系统提供的控件来进行简单的修改。

通过继承View类并复写onDraw()、onMeasure()、onKeyDown()等方法进行进一步的自定义。

转载于:https://my.oschina.net/diov/blog/539749

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值