Android:按钮onClick从ArrayList获取随机数据

时间:2018-06-04 01:36:07

标签: java android android-button

我使用java制作过滤器以选择特定的大陆,当您单击刷新时,您将获得随机过滤的数据 这是我的java代码

    public class Util {

    public static CountriesData getCountrie(){

        List<Country> mList = new ArrayList<>();
        mList.add(new Country(R.drawable.ae, "Emarat","asia"));
        mList.add(new Country(R.drawable.tm, "Turkmenistan","asia"));
        mList.add(new Country(R.drawable.bj, "Benin","Afriqua"));
        mList.add(new Country(R.drawable.va, "Seal of Virginia ","N.America"));
        mList.add(new Country(R.drawable.us, "USA","N.America"));
        mList.add(new Country(R.drawable.at, "Austria","Europe"));
        mList.add(new Country(R.drawable.pt, "Portugal","Europe"));
        mList.add(new Country(R.drawable.ki, "Kiribati ","S.America"));
        mList.add(new Country(R.drawable.cu, "Cuba","S.America"));
        mList.add(new Country(R.drawable.ht, "Haiti","S.America"));

        return new CountriesData(mList);

    }
}

我的问题是当我点击

时如何为我的按钮创建数据代码
   mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showRandomCountry();
        }
    });

    }

public void showRandomCountry(){
    schuffleAsia();
   // int r = new Random().nextInt(mList.size());

   mImageView.setImageResource(mList.get().getMcountry());
 //  mTextView.setText(mList.get(m).getmFact());

`

1 个答案:

答案 0 :(得分:0)

将此 function 放在Util课程中: -

 public Country getRandomCountry()
    {  
        return mList.get(new Random().nextInt(list.size()));//To get random item from the array.
    }

And For Getting Shuffled Array Use This function 的: -

 public ArrayList<Country> getShuffledList(int sizeOfArray){
 Util util = new Util();
 List<Country> shuffledList = new ArrayList<>();

    for(int i=0;i<sizeOfArray;i++)
    {
      shuffledList.add(util.getRandomCountry());
    }
 return shuffledList; 
}