Philip Kirkbride
Philip Kirkbride

Reputation: 22899

Android: Dynamic values in xml components?

I'm trying to learn the basics of Android development and I can't find any questions regarding dynamic values inside xml components.

Say I have template which defines several components in xml using this style:

<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>

Then I have a value which I have generated in java:

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

How can I reference the java value myCards[rnd] from inside the modified xml components?

enter image description here

Upvotes: 1

Views: 1885

Answers (2)

Gene Bo
Gene Bo

Reputation: 12103

As I understand it, Data Binding is currently the best practice solution for this requirement.

For getting started, you can check out section One Way Data Binding here: https://github.com/codepath/android_guides/wiki/Applying-Data-Binding-for-Views

Main points are:

  1. Enable data binding in gradle

    apply plugin: 'com.android.application'
    android {
        // ..
        dataBinding.enabled = true // put as last line in this block
    }
    
  2. Provide reference to the object you want use in xml with <data></data> element, where outter-most tag should be <layout></layout>

  3. On the data-binding layout reference Java object, set the view model

    mBinding.setMyCardViewModel(myCardViewModel)
    
  4. Access the object with {@myCardViewModel.someValue} notation in the xml

Upvotes: 3

Aritra Roy
Aritra Roy

Reputation: 15625

This is very simple.

Just reference the TextView in your Activity,

TextView textView = (TextView) findViewById(R.id.text1);

Now, all you need to do is set the text of this TextView,

textView.setText(myCards[rnd]);

That's it!

Note, that you should use the TextView's id as "@+id/text1".

Upvotes: 0

Related Questions