我有一个 GridView,我用 ArrayAdapter 的自定义子类填充。此适配器返回我已自定义为可选择的按钮(请参阅Android ImageButton with a selected state?)。到目前为止,这是有效的,单击按钮会选择它们(通过选择器背景可见)。
问题是:我无法从一开始就将这些按钮设置为选定状态。当我第一次启动视图时,它们只是显示未选中。
我创建了一个简单的测试项目来说明问题:
package com.example.buttonselection;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
public class MainActivity extends Activity {
public class SelectButtonAdapter extends ArrayAdapter<String> {
public SelectButtonAdapter(Context context) {
super(context, 0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String name = getItem(position);
View rowView = convertView;
if (rowView == null || !(rowView instanceof Button)) {
rowView = new Button(getContext());
((Button)rowView).setOnClickListener(new OnClickListener() {
public void onClick(View button) {
if (button.isSelected()){
button.setSelected(false);
} else {
button.setSelected(true);
}
}
});
}
Button button = (Button)rowView;
button.setText(name);
button.setBackgroundResource(R.drawable.button_selection);
button.setSelected(true); // this does not work
return button;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView grid = (GridView)findViewById(R.id.gridview);
SelectButtonAdapter adapter = new SelectButtonAdapter(this);
adapter.add("One");
adapter.add("Two");
adapter.add("Three");
grid.setAdapter(adapter);
}
}
因此,我什至无法恢复使用 onSaveInstanceState 保存的按钮的状态。我该如何解决或解决此问题?
我很感激任何帮助!
编辑:这是我的 button_selection.xml,虽然这应该没问题,因为稍后选择按钮可以正常工作。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="@color/bet_button_pressed" />
<stroke
android:width="2dip"
android:color="@color/white" />
</shape>
</item>
<item android:state_selected="true">
<shape>
<solid android:color="@color/bet_button_selected" />
<stroke
android:width="2dip"
android:color="@color/white" />
</shape>
</item>
<item>
<shape>
<gradient
android:angle="90"
android:startColor="@color/bet_button_dark_green"
android:endColor="@color/bet_button_light_green"
android:centerX="0.5"
android:centerY="0.5" />
<stroke
android:width="2dip"
android:color="@color/white" />
</shape>
</item>
</selector>