首页 > 移动平台 > 详细

android自定义控件

时间:2014-03-27 05:56:44      阅读:431      评论:0      收藏:0      [点我收藏+]

1.自定义组件(按钮)xml文件如下

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/id_paste_button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="@drawable/bottom_item_selector"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingBottom="4dp"
    android:paddingTop="4dp" >

    <ImageView
        android:id="@+id/btn_icon"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:src="@drawable/paste" />

    <TextView
        android:id="@+id/btn_txt"
        style="@style/myTextApprearence.micro.white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tab_paste" />

</LinearLayout>
bubuko.com,布布扣

2.这个按钮有两个属性是变的,一个是图片,一个是文字,在res/values/attrs.xml文件自定义两个属性:text, icon

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="BottomBarButton" >
        <attr name="android:text" type="text" />
        <attr name="android:icon" type="drawable" />
    </declare-styleable>
</resources>
bubuko.com,布布扣

java代码对这个自定义控件进行赋值

bubuko.com,布布扣
public class BottomBarBtn extends LinearLayout{

    public BottomBarBtn(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.bottom_bar_button, this, true);
        
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.BottomBarButton);
        //获取自定义属性‘text‘的值
        CharSequence iconDesc = ta.getText(R.styleable.BottomBarButton_android_text);
        //获取自定义属性‘icon‘的值    
        Drawable icon = ta.getDrawable(R.styleable.BottomBarButton_android_icon);
        TextView btnText = (TextView) findViewById(R.id.btn_txt);
        if(null != iconDesc){
            btnText.setText(iconDesc);
        }
        ImageView btnIcon = (ImageView) findViewById(R.id.btn_icon);
        if(null != icon){
            btnIcon.setImageDrawable(icon);
        }
        ta.recycle();
    }
}
bubuko.com,布布扣

 

3.布局文件中使用这个控件

bubuko.com,布布扣
<!--下面的两个属性是自定义的:icon, text-->
<com.ui.customview.BottomBarBtn
            android:id="@+id/id_paste_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:icon="@drawable/paste"
            android:text="@string/tab_paste" />
bubuko.com,布布扣

android自定义控件,布布扣,bubuko.com

android自定义控件

原文:http://www.cnblogs.com/baron89/p/3627022.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!