使用数组

时间:2017-09-19 23:38:07

标签: java android arrays android-studio-2.2

我尝试创建数组然后在ImageView上生成随机图像,但我的代码有问题... setBackgroundResource生成错误并且消息android studio是Cannot resolve method 'setBackgroundResource(int)'我的代码是:

@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button btn=(Button)findViewById(R.id.btn); 
    final RelativeLayout background = (RelativeLayout) findViewById(R.id.back); 
    Resources res = getResources(); 
    final TypedArray myImages = res.obtainTypedArray(R.array.myImages); 
    btn.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
            final Random random = new Random(); 
            int randomInt = random.nextInt(myImages.length()); 
            int drawableID = myImages.getResourceId(randomInt, -1); 
            background.setBackgroundResource(drawableID); 
        } 
    }); 
}

1 个答案:

答案 0 :(得分:1)

由于您在不同的上下文中访问数组,因此您应该将数据从类型化数组中提取到列表(或数组)中,并将其存储为成员变量。

private List<Integer> myImages;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn=(Button)findViewById(R.id.btn);
    final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
    myImages = getResourceList(R.array.myImages);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Random random = new Random();
            int randomInt = random.nextInt(myImages.size());
            int drawableID = myImages.get(randomInt);
            background.setBackgroundResource(drawableID);
        }
    });
}

public List<Integer> getResourceList(int arrayId){
    TypedArray ta = getResources().obtainTypedArray(arrayId);
    int n = ta.length();
    List<Integer> resourceList = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        int id = ta.getResourceId(i, 0);
        resourceList.add(id);
    }
    ta.recycle();

    return resourceList;
}