android自定义视图obtainStyledAttributes

时间:2013-05-03 10:58:55

标签: android android-layout android-xml

我对Android和Java都很陌生,所以请原谅我,如果我错过了一些明显的东西。

我想编写一个自定义View,我在通过otainStyledAttributes获取自定义属性时遇到问题。 我有一个非常简单的测试用例。 在Eclipse中,我使用默认活动创建一个空项目(包com.example.customview)。 然后我在res / values下添加了一个“attrs.xml”文件,其中包含以下内容:

  <resources>
    <declare-styleable name="testview">
       <attr name="test" format="string"/>
    </declare-styleable>
  </resources>

然后我在新的包“com.example.views”中添加一个新类“testview.java”。

package com.example.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.customview.R;

public class testview extends LinearLayout{

  public testview(Context context,AttributeSet attrs){
    super(context,attrs);

    TextView tv = new TextView(context);
    this.addView(tv);
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.testview, 0, 0);

    tv.setText(a.getString(R.styleable.testview_test));

    a.recycle();

}
}

最后在activity_main.xml中我有:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:my="http://schemas.android.com/apk/res/com.example.customview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <com.example.views.testview
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        my:test="test"
        />

</RelativeLayout>

我可以使用

获取my:test属性
attrs.getAttributeValue("http://schemas.android.com/apk/res/com.example.customview","test")

但如果我将该属性放在任何随机命名空间中,那也可以。

但是a.getString(R.styleable.testview_test)总是为空。

0 个答案:

没有答案