Keep image in GridView selected

2020-05-01 23:32发布

What I've done:


Hello Guys, I've got a GrindView which i filled over my Database. Now the Images shows up there and are scrollable. But when I click on it, they don't keep selected. To see which picture is selected I builded a Toastmessage which shows me what picture i clicked on with the onIemClickListner.

Question:


I'd like to let the Clicked Image, selected. So that you click on time on a Image in the GridView and afterwards it keeps selected. How can i realize that? I would be happy if there's a tutorial or a codesample, to see how it works.

The Code


This is what i tried that only the actual image gets keeps selected with the colors but it dosn't work the right way, sometimes it just changes..

//Hier wird gemerkt welches bild
        gridview.setOnItemClickListener(new OnItemClickListener() {

        boolean color = false;
            View old;
            View v;

            public void onItemClick(AdapterView<?> parent, View vv, int position, long id) {
                Toast.makeText(SFilterConfigActivity.this, "" + position, Toast.LENGTH_SHORT).show();

                v = vv;

                //gridview.setSelection(position);

               if (color == false){
                v.setBackgroundColor(0xFF00FF00);
                old = v;
                color = true;

               }

               else {
                   old.setBackgroundColor(0x00000000);
                   v.setBackgroundColor(0xFF00FF00);

                   color = false;

               }
            }
        });

Thx for you anwser in advance

safari

2条回答
够拽才男人
2楼-- · 2020-05-02 00:06

After you call setAdapter()

do it like this

setSelection(setSelected, true)

查看更多
何必那么认真
3楼-- · 2020-05-02 00:17

Following is the working code.

            if (color == false){
                vv.setBackgroundColor(getResources().getColor(R.color.green));
                old = vv;
                color = true;
            } else {
                old.setBackgroundColor(getResources().getColor(R.color.white));
                vv.setBackgroundColor(getResources().getColor(R.color.green));
                old=vv;
            }
查看更多
登录 后发表回答