How to set an image as background image on a click?

后端 未结 2 1549
囚心锁ツ
囚心锁ツ 2021-01-26 10:59

I have got an activity that shows a grid view with different images. When clicking on one of those images I want the clicked image to be the background image of another activity

2条回答
  •  余生分开走
    2021-01-26 11:57

    Get the resource ID of the image you want as the BG and save it to preferences.

        public void onItemClick(AdapterView parent, View v, int position, long id) {
            saveImageId(position);
        }
    
    private void saveImageId(int position) {
        int id = getImageId(); // get the R.drawable.* id of the image. You should be able to figure this out.
        Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
        ed.putInt("bg_image_id", id);
        ed.commit();
    }
    

    Now in your other activity, you can get the image id:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int id = prefs.getInt("bg_image_id", R.drawable.default_background); //Get image id, use default background if there isn't one.
    LinearLayout mLayout = (LinearLayout) findViewById(R.id.background_layout);
    mLayout.setBackgroundResource(id);
    

    Good luck

提交回复
热议问题