DataBinding: How to get resource by dynamic id?

前端 未结 6 1905
予麋鹿
予麋鹿 2020-12-24 02:12

I know that it is possible to reference resources in layout by their resource id:

android:text=\"@{@string/resourceName}\"

However, I would

6条回答
  •  北海茫月
    2020-12-24 02:41

    Another solution is to create a custom @BindingAdapter for it.

    @BindingAdapter({"format", "argId"})
    public static void setFormattedText(TextView textView, String format, int argId){
        if(argId == 0) return;
        textView.setText(String.format(format, textView.getResources().getString(argId)));
    }
    

    And then just provide the variables separately.

    You could use an array if you need multiple arguments, but in my case, one was sufficient.

提交回复
热议问题