我创建了一个自定义控件,并在attri.xml中定义了一些属性,但是我无法通过obtainStyledAttributes从declare styleable TypedArray获取值,你能帮我查一下我的代码有什么问题吗?
/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TopBar">
<attr name="title2" format="string" />
<attr name="titleTextSize2" format="dimension" />
<attr name="titleTextColor2" format="color" />
<attr name="leftTextColor" format="color" />
<attr name="leftBackground" format="color|reference" />
<attr name="leftText" format="string" />
<attr name="rightTextColor" format="color" />
<attr name="rightBackground" format="color|reference" />
<attr name="rightText" format="string" />
</declare-styleable>
</resources>
/res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.qihoo.foo.TopBar
android:id="@+id/topbar"
android:layout_width="match_parent"
android:layout_height="45dp"
myapp:leftBackground="@drawable/left"
myapp:leftText="Back"
myapp:leftTextColor="#ffffff"
myapp:rightBackground="@drawable/right"
myapp:rightText="Move"
myapp:rightTextColor="#ffffff"
myapp:title2="title"
myapp:titleTextColor2="#123412"
myapp:titleTextSize2="18sp"
>
</com.qihoo.foo.TopBar>
</LinearLayout>
/com.foo.samples/TopBar.java
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.Toolbar);
// I can't get any value from below codes
mLeftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
mLeftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
mLeftText = ta.getString(R.styleable.TopBar_leftText);
mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
mRightBackground = ta.getDrawable(R.styleable.TopBar_rightBackground);
mRightText = ta.getString(R.styleable.TopBar_rightText);
mTitleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize2, 10);
mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor2, 0);
mTitle = ta.getString(R.styleable.TopBar_title2);
ta.recycle();
}