在 JSON 文件的 xml 布局中设置文本

Set text inside xml layout from JSON file

我正在寻找一种方法来做到这一点。 我在 may 项目中有一个 JSON 文件,例如 mystrings.json,它是这样的:

{
"ErrorCodes.1": "Hai superato il tempo limite",
"ErrorCodes.2": "Hai superato il tempo limite"
}

我想这样使用这个json:

<TextView
  android:text="@ErrorCodes.1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>

有办法完成吗? 我正在搜索但没有结果。 提前致谢。

您可以使用 Data Binding

执行此操作
  1. 解析您的 JSON 文件并将其设置在模型 class(即 UserModel、ErrorModel 等)中。
  2. 将该模型 class 绑定到 xml 文件

    <data>
      <variable name="user" type="com.example.User"/>
    </data>
    
  3. 设置值 TextView

    <TextView android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@{user.error}"/>
    
  4. 在您的 Activity

    中执行绑定
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
        User user = get your model class here;
        binding.setUser(user);
    }
    

这里有Data Binding的一些教程,大家可以参考一下

Working with Data Binding Android 作者:拉维·鲁帕雷利亚
DataBinding: how to develop Android apps faster
No More findViewById 乔治·芒特
Develop apps faster using Data Binding – Part 1 作者 Chintan Rathod