简体   繁体   中英

How to get variable values from java to xml file in android?

I have got some value from another activity in .java file. Now I want to use that value in my .xml file. How should I approach this. Should I generate a dynamic xml? Can I set some value in xml run-time?

My .java file is:

package com.example.shiza.chemistrylabapp;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class ExperimentExplaination extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_experiment_explaination);
        Intent i = getIntent();

        int position = i.getIntExtra("Position",0);
    }
}

Now, I want to use position for xml file.

.xml file:

<RelativeLayout 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.shiza.chemistrylabapp.ExperimentExplaination">
</RelativeLayout>

Add an ID to your relative layout resource:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"     
    android:id="@+id/layout
    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.shiza.chemistrylabapp.ExperimentExplaination">
</RelativeLayout>

Then in your class, you can get that reference and set the value.

RelativeLayout rl = (RelativeLayout)findViewById(R.id.layout);

Then set whatever attribute of the relative layout you want

//Example
int width = 90;
rl.setWidth = width;

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