gpt4 book ai didi

java - Android:xml 组件中的动态值?

转载 作者:行者123 更新时间:2023-12-02 03:00:01 25 4
gpt4 key购买 nike

我正在尝试学习 Android 开发的基础知识,但找不到任何有关 xml 组件内动态值的问题。

假设我有一个模板,它使用这种样式在 xml 中定义了多个组件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#a6c"
android:padding="16dp"
android:gravity="bottom">

<TextView android:id="@android:id/text1"
style="?android:textAppearanceLarge"
android:textStyle="bold"
android:textColor="#fff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/card_back_title" />

</LinearLayout>

然后我有一个在 java 中生成的值:

    String[] myCards = getResources().getStringArray(R.array.cards);
int rnd = new Random().nextInt(myCards.length);
Log.i("myApp", myCards[rnd]);

如何从修改后的 xml 组件内部引用 java 值 myCards[rnd]

enter image description here

最佳答案

据我了解,数据绑定(bind)是目前满足此需求的最佳实践解决方案。

要开始使用,您可以查看此处的单向数据绑定(bind)部分: https://github.com/codepath/android_guides/wiki/Applying-Data-Binding-for-Views

要点是:

  1. 在 gradle 中启用数据绑定(bind)

    apply plugin: 'com.android.application'
    android {
    // ..
    dataBinding.enabled = true // put as last line in this block
    }
  2. 通过 <data></data> 提供对要在 xml 中使用的对象的引用元素,其中最外面的标签应该是 <layout></layout>

  3. 在数据绑定(bind)布局引用Java对象上,设置 View 模型

    mBinding.setMyCardViewModel(myCardViewModel)
  4. 使用 {@myCardViewModel.someValue} 访问对象xml 中的表示法

关于java - Android:xml 组件中的动态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com