【问题标题】:Set text inside xml layout from JSON file从 JSON 文件设置 xml 布局内的文本
【发布时间】:2016-07-14 13:14:42
【问题描述】:

我正在寻找一种方法来做到这一点。 我有一个 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"/>

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

【问题讨论】:

  • 不,你不能做这样的解析。您必须解析 json 并将 json 值设置为 textview

标签: android json xml string android-contentprovider


【解决方案1】:

您可以使用Data Binding 来执行此操作

  1. 解析您的 JSON 文件并将其设置在模型类中(即 UserModel、ErrorModel 等)。
  2. 将该模型类绑定到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 by Ravi Rupareliya
DataBinding: how to develop Android apps faster
No More findViewById by George Mount
Develop apps faster using Data Binding – Part 1 by Chintan Rathod

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多