我有一个gridView,它显示来自API的图像。单击该项目我想要用某种颜色突出显示图像边框,再次点击该项目它应该返回到之前的状态。我创建了一个选择器类,并尝试在ListSelector中设置它,但它不起作用。 这是我的示例代码:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/grid_view"
tools:context=".MainActivity"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth"
android:layout_margin="10dp"
android:listSelector="@drawable/states_grid_view">
</GridView>
Selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<stroke android:width="4dp" android:color="#3c77d6"/>
<corners android:radius="10dp"/>
</shape>
</item>
</selector>
states_grid_view.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- grid view item pressed state -->
<item
android:state_pressed="true"
android:drawable="@android:color/holo_red_light"
/>
<!-- grid view item selected state -->
<item
android:drawable="@drawable/selector"
/>
</selector>
我只是想知道我做错了什么,也想知道如何再次点击该项目进入以前的状态。
答案 0 :(得分:0)
我在代码中看不到任何错误,事实上它在我的机器上工作正常。 这是活动类代码。
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
GridView gridview = (GridView) findViewById(R.id.pulltorefresh_gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(SplashActivity.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.sample1,
R.drawable.sample2,
R.drawable.sample3,
R.drawable.sample4,
R.drawable.sample5,
R.drawable.sample6,
R.drawable.sample7,
R.drawable.sample8
};
}
}