1

我对 StateListDrawable 有一个奇怪的问题,或者(可能)我遗漏了一些东西。我为它创建了一个测试应用程序,并且发生了同样的问题。所以,这是我在文件 test_selection.xml 中的 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>

这是一个非常简单的选择器,为选定状态绘制红色,为未选定状态绘制白色矩形。

我的 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();
  };
 }
}

当 Activity 启动时,我尝试使用 SELECTED 值设置 Drawable(StateListDrawable)的状态。看起来一切都很简单....但问题是没有显示状态。如果稍后我单击一个按钮并执行 updateView() 方法,则状态会发生变化。我的问题在哪里?我哪里错了?

非常感谢 Max

4

1 回答 1

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}

再见麦克斯

于 2010-08-26T13:40:17.380 回答