4

我正在实现我自己的自定义 DialogPreference 子类,如下所示:

public class MyCustomPreference extends DialogPreference
{
    private static final String androidns = "http://schemas.android.com/apk/res/android";

    private String mDialogMsg;

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

        mDialogMsg = attrs.getAttributeValue(androidns, "dialogMessage");

        ...
    }

    ...
}

如您所见,我获取了dialogMessageXML 属性并将其保存在成员变量mDialogMsg中。

我的问题是:我当前的代码不允许将dialogMessageXML 属性指定为 XML 中的字符串资源 ID。

换句话说,这有效:

android:dialogMessage="Hello world!"

但这不会:

android:dialogMessage="@string/hello_world"

如果我在 XML 中将其指定为资源 id,则资源id将保存到mDialogMsg,而不是字符串资源本身。现在,我知道我可以这样做:

context.getString(attrs.getAttributeValue(androidns, "dialogMessage"))

但随后用户将无法在 XML 中输入普通字符串(即非资源 ID)。我想给用户两种选择。我该怎么做呢?

4

3 回答 3

7
int resId = attrs.getAttributeResourceValue(androidns, "dialogMessage", 0);
if(resId != 0){
    mDialogMsg = getContext().getResources().getString(resId);
} else{
    mDialogMsg = attrs.getAttributeValue(androidns, "dialogMessage");
}
于 2012-11-29T04:08:01.930 回答
0

我不确定我是否完全理解您的问题,但如果我理解了,字符串资源实际上会保存为整数值。我在应用程序中创建了以下函数来获取字符串值

public static String getToastString(int res, Context c)
    {
        String toast = "";
        toast = c.getResources().getString(res);

        return toast;
    }

然后我可以传递资源和上下文来获取值

于 2012-11-29T03:57:01.633 回答
0

1)声明自定义属性:

<declare-styleable name="CustomItem">
  <attr name="item_text" format="string"/>
</declare-styleable>

2)获取它的值:

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

  mTextView = (TextView) findViewById(R.id.text_view);

  final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomItem);
  try {
    setText(a.getString(R.styleable.CustomItem_item_text));
  } finally {
    a.recycle();
  }
}

public final void setText(String text) {
  mTextView.setText(text);
}

public final void setText(@StringRes int resId) {
  mTextView.setText(resId);
}

3)在布局中使用它:

<com.example.CustomItem
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  app:item_text="@string/welcome_text"
  />

<com.example.CustomItem
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  app:item_text="Hello!"
  />
于 2018-05-06T07:19:06.570 回答