Android: Replacing images in GridView array after OnItemClick

前端 未结 1 448
走了就别回头了
走了就别回头了 2021-01-23 06:44

I have a grid view that looks roughly like this (each image will be a different in the end):

\"enter

相关标签:
1条回答
  • 2021-01-23 06:48

    To do this, we need to do two things:

    1. Change the drawable of the item when it is clicked. In onItemClick(...), change the drawable for the View that is passed to you. This View will be the same one that you created in getView(...) of your adapter.

    2. Make sure that the item is shown with the correct drawable the next time it comes on screen. To do this, keep track of the state of each item. Every time you make a view for the item in getView(...), assign it the correct drawable for its state.


    Here is an example. I am assuming ImageAdapter is a subclass of ArrayAdapter. If not, then you will need to modify this code to work with what you are doing.

    Put these somewhere:

    private static final int WHITE = 0;
    private static final int TEAL = 1;
    private static final int MAROON = 2;
    private List<Integer> mStates = new ArrayList<Integer>();
    

    This goes in your ImageAdapter:

    // Map each state to its graphics.
    private Map<Integer, Integer> mStateResources = new HashMap<Integer, Integer>();
    mStateResources.put(WHITE, R.drawable.white);
    
    public void add(...) {
        super.add(...);
    
        // The new item will start as white.
        mStates.add(WHITE);
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {
        //ImageView image = ...
    
        // Set the correct image for the state of this item.
        int state = mStates.get(position);
        int resId = mStateResources.get(state);
        image.setImageResource(resId);
    }
    

    In your OnItemClickListener:

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        // Change the image and state for this item.
        int nextState;
        switch(mStates.get(position)) {
        case WHITE:
            nextState = TEAL;
            break;
        case TEAL:
            nextState = MAROON;
            break;
        case MAROON:
            nextState = WHITE;
            break;
        }
    
        // Set the new state and image for this item.
        mStates.put(position, nextState);
        int resId = mStateResources.get(nextState);
        image.setImageResource(resId);
    }
    
    0 讨论(0)
提交回复
热议问题