2015-05-27 66 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;