2017-09-19 12 views
1

配列を作成してImageViewでランダムな画像を生成しようとしていますが、コードに問題があります... setBackgroundResourceはエラーを生成し、メッセージアンドロイドスタジオはCannot resolve method 'setBackgroundResource(int)'です。あなたが別の文脈で配列にアクセスしているのでImageViewでランダムに画像を生成

@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

、リスト(または配列)に型指定された配列のうちデータを取得し、メンバ変数としてそれを保存する必要があります。

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; 
} 
関連する問題