2012-04-16 31 views
2

的風格,我有這個XML改變編程我的RelativeLayout

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    style="@style/FragmentSecondary" > 
    <LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" 
     android:layout_alignParentTop="true"/> 

<RelativeLyout> 

我的風格是他的風格=「@風格/ FragmentSecondary」,要編程上改變它的風格= @風格/ FragmentTrains。 我不想重寫另一個xml。我需要把它寫在代碼中。我怎樣才能做到這一點?

+0

可能重複:http://stackoverflow.com/questions/2016249/how-to-programmatically-setting-style-attribute-in-a-view – 2012-04-16 16:16:18

回答

0

我不相信你可以以編程方式設置樣式。爲了解決這個問題,你可以創建一個指定樣式的模板佈局xml文件,例如在res /佈局創建tvtemplate.xml爲具有以下內容:

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="This is a template" 
     style="@style/my_style" /> 

然後膨脹此實例化新的TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null); 

希望這會有所幫助。

也可參考此LINK & set style from code