Issue
How can I pass an image/picture as an argument to a function in android studio?
I have pic1.jpg, pic2.jpg, pic3.jpg, and pic4.jpg in drawable folder, and I have something like this:
private void exampleFunction() {
ImageButton key1 = (ImageButton) findViewById(com.example.game.R.id.key1);
ImageButton key2 = (ImageButton) findViewById(com.example.game.R.id.key2);
ImageButton key3 = (ImageButton) findViewById(com.example.game.R.id.key3);
ImageButton key4 = (ImageButton) findViewById(com.example.game.R.id.key4);
if ( condition1) {
key1.setImageResource(com.example.game.R.drawable.pic1);
key2.setImageResource(com.example.game.R.drawable.pic2);
}
else if ( condition2 ) {
key3.setImageResource(com.example.game.R.drawable.pic3);
key4.setImageResource(com.example.game.R.drawable.pic4);
}
}
How can I do it like this:
private void exampleFunction() {
ImageButton key1 = (ImageButton) findViewById(com.example.game.R.id.key1);
ImageButton key2 = (ImageButton) findViewById(com.example.game.R.id.key2);
ImageButton key3 = (ImageButton) findViewById(com.example.game.R.id.key3);
ImageButton key4 = (ImageButton) findViewById(com.example.game.R.id.key4);
if ( condition1) {
assignPics (key1, key2, pic1, pic2);
}
else if ( condition2 ) {
assignPics (key3, key4, pic3, pic4);
}
}
private void assignPics( ImageButton p1, ImageButton p2, ...how should I receive picture1-2 here ) {
p1.setImageResource( ?? picture1 ?? );
p2.setImageResource( ?? picture2 ?? );
}
Solution
Ids are int
values in Android, so assignPics
function should look as follows:
private void assignPics(ImageButton p1, ImageButton p2, int id1, int id2) {
p1.setImageResource(id1);
p2.setImageResource(id2);
}
Answered By - Yash Mittal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.