简体   繁体   中英

How to show images in a button from a dynamic list?

I'm doing an app in Android and I want to have a list of images that will be displayed in the background of a button randomly every time I click it.

Which is the best way to store them? I would like to reduced the list every time I click the button to not show that image again

You can do it by removing the last item/image every time you click and add some new item/image. Here's the example of simple arraylist in basic listview. Add listview in your activity layout and add this code to activity and you'll get simple list that add and remove items with every click on the button. Technically your list can have size 2 forever if you don't modify clauses by your preferences and needs.

    ListView list = (ListView) findViewById(R.id.listView);
    Button button = (Button) findViewById(R.id.button);

    List<String> arrayList = new ArrayList<String>();

    ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    list.setAdapter(adapter);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // add item
            arrayList.add(newItem);

            // make sure you have at least two items in list so you don't have empty list and remove last item
            if(arrayList.size())
                arrayList.remove(lastItem);

            // make sure your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM