3

私は Android と Java にかなり慣れていないので、明らかな何かが欠けている場合はご容赦ください。

カスタム ビューを作成したいのですが、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) は常に null です。

4

0 に答える 0