美文网首页
自定义控件

自定义控件

作者: rikkka | 来源:发表于2015-06-02 16:31 被阅读0次

关于如何在XML文件中设置控件属性。参考:

http://blog.csdn.net/tianjf0514/article/details/7520988

1.在res/value文件下定义一个attrs.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <declare-styleable name="CommonTitle">  
        <attr name="text" format="string"></attr>  
        <attr name="textColor" format="color"></attr>  
        <attr name="textSize" format="dimension"></attr>  
    </declare-styleable>  
</resources> 

2.在xml文件中使用该组件。

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:myAndroid="http://schemas.android.com/apk/res/com.xdu"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent" >  
      
    <com.xdu.view.MyView  
        android:layout_width="fill_parent"  
        android:layout_height="50dip"  
        myAndroid:text="@string/str_title"  
        myAndroid:textColor="@android:color/darker_gray"  
        myAndroid:textsize="@dimen/text_size" />  
  
</LinearLayout> 

3.在自定义组件的java代码中,可以获取xml文件中的设置数值:

public MyView(Context context, AttributeSet attrs) {  
    super(context, attrs);  
    mContext = context;  
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);  
    mText = a.getString(R.styleable.MyView_text);  
    mTextColor = a.getColor(R.styleable.MyView_textColor,    
            0XFFFFFFFF);    
    mTextSize = a.getDimensionPixelSize(R.styleable.MyView_textSize, 0);  
    a.recycle();  
} 

相关文章

网友评论

      本文标题:自定义控件

      本文链接:https://www.haomeiwen.com/subject/imrdqttx.html