我正在尝试突出显示一个GridView
元素的背景。
Activity.java:
private CustomAdapter ca;
public void onCreate(Bundle _) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
// ...
GridView gw = (GridView) findViewById(R.id.gridview);
gw.setAdapter(ca = new CustomAdapter(this));
gw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// attempt 1:
view.setSelection(true);
// attempt 2:
gw.setSelection(position);
// attempt 3:
gw.setItemChecked(position, true);
// tried everything WITH and WITHOUT this:
ca.notifyDataSetChanged();
}
});
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private LayoutInflater inflater;
public CustomAdapter(Context c) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Download items async, and call...
notifyDataSetChanged();
// ... in a callback
}
// getItem(), getCount() and getItemId() implemented here
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if( convertView!=null ) view = convertView;
else {
view = inflater.inflate(R.layout.grid_item, parent, false);
// calculate height so that an item is a square
int height = parent.getHeight();
if( height>0 ) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = height/3;
}
}
ImageView image = (ImageView) view.findViewById(R.id.image);
image.setImageBitmap( getItemImageBitmap(position) );
return view;
}
}
activity_layout.xml
<GridView android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchMode="columnWidth"
android:numColumns="3"
android:drawSelectorOnTop="false"
android:choiceMode="singleChoice"
android:listSelector="@drawable/grid_selector"
/>
<!-- I've tried any combination of those last three params I could think of -->
grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image"
android:background="@drawable/grid_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
grid_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@android:color/holo_red_dark" />
<item android:drawable="@android:color/transparent" />
</selector>
我尝试在网格视图中将grid_selector
作为项目背景或listSelector
属性。
我的目标是在用户点击时突出显示一个项目(之后直到选择其他项目)。
答案 0 :(得分:0)
所以我的神奇组合是:
gw.setItemChecked(position, true);
中的Activity.java
就足够了,CustomAdapter.java
,
listSelector="@drawable/grid_selector"
必须从activity_layout.xml
移除,grid_item.xml
必须背景,android:state_checked="true"
中使用android:state_selected="true"
代替grid_selector.xml
。