2015-05-27 68 views
0

我已经从.java文件中的其他活动中获得了一些价值。现在我想在我的.xml文件中使用该值。我应该如何解决这个问题。我应该生成一个动态的XML?我可以在xml运行时设置一些值吗?如何从android中获取变量值从java到xml文件?

我的java文件是:

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); 
    } 
} 

现在,我想用位置xml文件。

.xml文件:

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

回答

1

添加ID到您的相对布局资源:

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

然后在你的类,你可以得到参考和设置的值。

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

然后设置任何你想要的相对布局的属性

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