在 res/values目录下的attrs.xml中定义资源
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="duration"></attr>
<declare-styleable name="myButton">
<attr name="duration"></attr>
</declare-styleable>
</resources>
定义一个自定义组件
public class MyButton extends Button
{
int duration;
public MyButton(Context context,AttributeSet attr)
{
super(context,attr);
TypedArray typedArray=context.obtainStyledAttributes(attr,R.styleable.myButton );
duration=typedArray.getInt(R.styleable.myButton_duration,0);
this.setText(duration+"duration");
}
}
在布局文件中使用自定义组件,记得设置好命名空间,一开始res-auto部分按照网上的说法应该是自定义组件所在的包名,but我使用是无线错,然后神奇发现可以这样
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:my="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<com.example.my.MyButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
my:duration="10"/>
</LinearLayout>