2010-08-25 113 views
1

我有一個StateListDrawable奇怪的問題,或許(可能)我失去了一些東西。我爲它創建了一個測試應用程序,併發生同樣的問題。所以,這是我在文件test_selection.xmlAndroid刷新StateListDrawable問題

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_selected="true"> 
    <shape android:shape="rectangle" android:background="#ff0000"> 
    <corners android:radius="10dp" /> 
    <gradient android:startColor="#ff5555" 
    android:endColor="#ff5555" android:angle="0" /> 
    </shape> 
</item> 
<item android:state_selected="false"> 
    <shape android:shape="rectangle" android:background="#eeeeee"> 
    <corners android:radius="10dp" /> 
    <gradient android:startColor="#eeeeee" 
    android:endColor="#eeeeee" android:angle="0" /> 
    </shape> 
</item> 
</selector> 

這是一個非常簡單的選擇是畫一個紅色的選中狀態和白色矩形未選定一個StateListDrawable國土資源。

我的main.xml模板非常簡單。我只是使用一個TextView來使用選擇作爲背景。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<TextView android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:text="@string/hello" 
    android:textSize="30dp" android:id="@+id/test_view_example" android:background="@drawable/test_selection"/> 
<Button android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:id="@+id/refresh" 
    android:onClick="updateView" android:text="refresh"></Button> 
</LinearLayout> 

我的活動代碼也很簡單。

public class TestDrawableStateActivity extends Activity { 

private final static int[] SELECTED_STATE = { android.R.attr.state_selected }; 
private final static int[] UNSELECTED_STATE = {}; 

private TextView textView; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    textView = (TextView) findViewById(R.id.test_view_example); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    // Carichiamo la Drawable 
    if(textView.getBackground().setState(SELECTED_STATE)){ 
    textView.invalidate(); 
    } 
} 

public void updateView(View view) { 
    if(textView.getBackground().setState(SELECTED_STATE)){ 
    textView.invalidate(); 
    }; 
} 
} 

當活動開始我嘗試與選擇的值設置我的繪製對象(在StateListDrawable)的狀態。 這似乎都非常簡單....但問題是狀態沒有顯示。如果稍後我點擊一個按鈕並執行方法updateView(),狀態就會改變。 我的問題在哪裏?我錯在哪裏?

Thankx很多 最大

回答

0

最後我找到了解決辦法。它應該是同樣的事情,但事實並非如此。我用這個的onCreate()版本

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    textView = (TextView) findViewById(R.id.test_view_example); 
    textView.setSelected(true); 
} 

令人驚訝的叫setSelected(true)比調用setState()int[]{android.R.attrs.state_selected}不同。這是由於內部視圖狀態。

再見 最大