I am trying to make an application that takes a random image from an array and displays it in an image view. What I want to do now, and I can't, is that depending on the image that appears I want different things to happen, I tried a switch but it doesn't work, what am I doing wrong?
My code:
public class MainActivity extends Activity {
Button b1, b2,b3,b4,b5;
ImageView iv1,iv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
b3=(Button)findViewById(R.id.b3);
b4=(Button)findViewById(R.id.b4);
b5=(Button)findViewById(R.id.b5);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void Accion1 (View view){
final TypedArray imgs = getResources().obtainTypedArray(R.array.RandomImages);
final Random rand = new Random();
final int rndInt = rand.nextInt(imgs.length());
final int rID = imgs.getResourceId(rndInt, 0);
iv2.setImageResource(rID);
b1.setVisibility(View.INVISIBLE);
b2.setVisibility(View.VISIBLE);
}
public void Accion2(View view){
b2.setVisibility(View.INVISIBLE);
switch (iv2.getId()){
case 1:
iv2.setImageResource(R.drawable.imagen1);
b3.setVisibility(View.VISIBLE);
break;
case 2:
iv2.setImageResource(R.drawable.imagen2);
b4.setVisibility(View.VISIBLE);
break;
case 3:
iv2.setImageResource(R.drawable.imagen3);
b5.setVisibility(View.VISIBLE);
break;
}
}
}
The following occurs to me:
You can create a TypedArray containing the possible ids
https://developer.android.com/guide/topics/resources/more-resources.html#TypedArray
For example:
You get the values like this:
You get the drawable like this: