2011-01-22 102 views
2

在Android資源xml中引用主題的屬性值時使用問號(?)而不是(@)。如下面的ListViewCustomStyle:Android訪問屬性參考

<ListView 
    android:id="@+id/MainScreenListView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    style="?ListViewCustomStyle"/> 

如何在代碼中使用ListViewCustomStyle的值?如果我試試它的正常方式,即

com.myapp.R.attr.ListViewCustomStyle 

然後代碼崩潰。有沒有特別的方法可以訪問它,因爲它是對一個項目的引用而不是實際的項目?

回答

5

它可能只是因爲你在那裏寫了ListRowCustomStyle和ListViewCustomStyle在你的xml中而崩潰。

我這樣做的方式是例如在標籤style =「@ style/my_button」(沒有android:在它之前)。然後,您可以在values/styles.xml文件中定義您的樣式,例如

<?xml version="1.0" encoding="utf-8"?> 
<resources xmlns:android="http://schemas.android.com/apk/res/android"> 
    <style name="my_button" parent="@android:style/Widget.Button"> 
     <item name="android:gravity">center_vertical|center_horizontal</item> 
     <item name="android:textColor">#FFFFFFFF</item> 
    ... 
     </style> 
</resources> 

您可以通過使用id R.style.my_button

+1

Woops ListRowCustomStyle是一個錯字;我已經修復 – 2011-01-22 20:09:31

2

相信在XML訪問代碼的風格,你想寫

風格= 「@風格/ ListViewCustomStyle」

無論如何,如何在代碼中使用它?

我最後一次檢查,這是不可能的:(

我一招做到了:

  1. 創建佈局文件,如下例:

    <Button 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    style="@style/MyCustomStyle"/> 
    
  2. 當您想要在代碼中添加具有自定義樣式的對象時,您必須使用剛剛創建的此佈局誇大它:

LayoutInflater inflater = LayoutInflater.from(this); // this = activity or context 
Button button = (Button) inflater.inflate(R.layout.myButtonWithMyStyle, null); //use the same layout file as above 
button.setText("It works!"); 
myView.addView(button); 

這比在代碼中創建一個按鈕相當慢。如果您使用此方法同時創建Views的Hundread,則可能會出現問題。少於我認爲你可以處理它。

+0

好吧,現在它顯示了一切(有一些bug隱藏了一些代碼) – 2011-01-31 11:58:55