android - gridview 我想让它点击一项 那项变红 但是我的代码的效果很诡异,点击后那项会变红,但是有的没点的项也变红。

浏览:29日期:2022-12-03

问题描述

public class MainActivity extends Activity { GridView grid; ImageView imgview; int img=R.drawable.ic_launcher; int []imageids=new int []{img,R.drawable.sxq1,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,img,R.drawable.sxq2,img,R.drawable.sxq1,img,img,img,img,img,img,img,img}; @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);List<Map<String,Object>> listItems=new ArrayList<Map<String,Object>>();for(int i=0;i<imageids.length;i++){Map<String, Object> listItem = new HashMap<String, Object>(); listItem.put('image', imageids[i]); listItems.add(listItem);} // 获取显示图片的ImageViewimgview = (ImageView) findViewById(R.id.imageview); // 创建一个SimpleAdapter SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems // 使用/layout/cell.xml文件作为界面布局 , R.layout.cell, new String[] { 'image' }, new int[] { R.id.image1 }); grid = (GridView) findViewById(R.id.grid1); // 为GridView设置Adapter grid.setAdapter(simpleAdapter); // 添加列表项被选中的监听器 grid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent, View view, int position, long id){ // 显示当前被选中的图片 imgview.setImageResource(imageids[position]); System.out.println('select');}@Overridepublic void onNothingSelected(AdapterView<?> parent){} }); // 添加列表项被单击的监听器 grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id){ // 显示被单击的图片 imgview.setImageResource(imageids[position]); view.setBackgroundColor(Color.RED); System.out.println('click');} }); } @Override public boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true; } @Override public boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) { return true;}return super.onOptionsItemSelected(item); }}

问题解答

回答1:

这个和gridview的item复用有关,这个是很常见的吧,你点position 0,那么你滑到第二页第一个也会变红,因为它复用了那个红色的。复用是为了内存,题主百度下 listview item复用吧,这是一个很经典古老的东西了。最好的做法是,用java类把每个item的红色状态记录下来,这样就不会有问题了

回答2:

你通过View child = parent.getChildAt(position);来获取点击视图,然后再调用child.setBackgroundColor(Color.RED);看效果如何。

相关文章: