简体   繁体   中英

Inserting java variables into xml in android studio

So I've created a java class that generates a string that I would like to display in an XML GridLayout TextView, but I've been having trouble figuring out how to transfer the variable I've created in my java class into a usable format in XML.

I've tried simply creating a TextView in Java but I'm trying to create a vertical design with text directly over a button and GridLayout seems like the best way to do that.

Here's what my code boils down to

String output;

//determine value of string

And here's my XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.reid.agerangecalculator.CalculateActivity">

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/GridLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:columnCount="1"
    android:rowCount="2"
    android:orientation="horizontal"
    tools:context=".GridXMLActivity" >

    <TextView
        android:id="@+id/textview1"
        android:layout_column="0"
        android:layout_row="0"
        android:text= ""/>

    <Button
        android:id="@+id/button3"
        android:layout_column="0"
        android:layout_gravity="left|top"
        android:layout_row="1"
        android:text="Button" />

</GridLayout>



</LinearLayout>

your Textview in xml layout

<TextView
        android:id="@+id/textview1"
        android:layout_column="0"
        android:layout_row="0"
        android:text= ""/>

Then, in your activity class:

 String output;
    // globally 
    TextView textView1 
    //in your OnCreate() method
    textView1  = (TextView)findViewById(R.id.textview1);
    textView1.setText(output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM