This question already has answers here:
how to access the drawable resources by name in android
(7 answers)
Closed 6 years ago.
I have to dynamically get some resources from the R file.
For example, let's say I have to dynamically generate ImageView and dynamically get a drawable to put inside it.
I don't know how many ImageView I have to generate; there may be 10, 50 or 100 so I have to do everything dynamically.
My main problem is to get dynamically the drawable from the R file.
Lets say I have this drawable:
R.drawable.img1
R.drawable.img2
R.drawable.img3
R.drawable.img4
I should do something like this:
for(int i = 0; i < 10; i++){
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.img + i);
}
How can I "build" this line of code: R.drawable.img + i
How can I reach my goal?
At first make sure your image is jpg or png
You can try with this
for(int i = 0; i < 10; i++)
{
ImageView iv = new ImageView(this);
int imageResource = context.getResources().getIdentifier("#drawable/img "+i.replace(".jpg", ""), null,context.getPackageName());
iv.setImageResource(imageResource);
}
final int []imageArray=
{R.drawable.img1,R.drawable.img2,R.drawable.img3};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run() {
//randomimg.setImageResource(imageArray[i]);
//hEAR CREATE dynamic image view and set image resource
i++;
if(i>imageArray.length-1)
{
i=0;
}
handler.postDelayed(this, 5000); //for interval...
}
};
handler.postDelayed(runnable, 5000);
put above code in your activity. and set image resource it work for me.
Related
How can I declare some ImageViews programmatically in oncreate method ? I want to have something like this:
for (int i =1 ; i<=10;i++){
ImageView image+i = (ImageView)findViewById(R.id.image+i);
}
I don't know if it is possible something like this, or you have to make it imageview by imageview.
ImageView[] imageViews = new ImageView[10];
for (int i =1 ; i<= 10; i++){
int id = getResources().getIdentifier("image"+i, "id", getPackageName());
imageViews[i - 1] = (ImageView)findViewById(id);
}
getIdentifier returns the resource's id associate to the name, the first parameter, and you could use an array to store the view's reference.
you can use something like this method
LinearLayout layout = (LinearLayout)findViewById(R.id.imageLayout);
for(int i=0;i<10;i++)
{
ImageView image+i = new ImageView(this);
image+i.setLayoutParams(new android.view.ViewGroup.LayoutParams(80,60));
image+i.setMaxHeight(20);
image+i.setMaxWidth(20);
// Adds the view to the layout
layout.addView(image);
}
go through this tutorial and this too.
I recently started making a chess-like game for android. The first thing I needed was to make the 8 by 8 board. I figured adding 64 buttons and organizing them in the XML wouldn't be much efficient, so I found a way to create them programmatically using a simple 8x8 matrix of buttons. Until this point, everything worked as intended, and I had this:
The next thing I tried was to change the colors of the buttons to match a chessboard. On the internet I found some ways of doing it, but pretty much all of them just made my buttons invisible, and did not change their color.
Here's the onCreate method (the only thing I modified so far):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
//GETTING SCREEN DIMENSIONS
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
//SETTING THE BOARD
int TILESIZE = width/8;
LinearLayout back = (LinearLayout) findViewById(R.id.back);
LinearLayout[] rows = new LinearLayout[8];
Button[][] tiles = new Button[8][8];
for(int i = 0; i < 8; i++){
rows[i] = new LinearLayout(this);
back.addView(rows[i]);
for(int j = 0; j < 8; j++){
tiles[i][j] = new Button(this);
tiles[i][j].setWidth(TILESIZE);
tiles[i][j].setHeight(tiles[i][j].getWidth());
if((i + j) % 2 == 0){
tiles[i][j].setBackgroundColor(0xFFFFFFFF);
tiles[i][j].invalidate();
}
else{
//TODO: Make tiles black
}
rows[i].addView(tiles[i][j]);
}
}
}
The XML file contains a single vertical linear layout called back.
My question is how can I make the buttons change color, and where am I doing something wrong. I would also gladly accept alternative (or better) ways to make the board.
Change your loop like this and try
for(int i = 0; i < 8; i++){
rows[i] = new LinearLayout(this);
for(int j = 0; j < 8; j++){
tiles[i][j] = new Button(this);
tiles[i][j].setWidth(TILESIZE);
tiles[i][j].setHeight(tiles[i][j].getWidth());
if((i + j) % 2 == 0){
tiles[i][j].setBackgroundColor(0xFFFFFFFF);
tiles[i][j].invalidate();
}
else{
//TODO: Make tiles black
}
rows[i].addView(tiles[i][j]);
}
back.addView(rows[i]);
}
Change your if loop like this:
if((i + j) % 2 == 0)
tiles[i][j].setBackgroundColor(android.R.color.holo_blue_dark);
else
tiles[i][j].setBackgroundColor(android.R.color.holo_red_dark);
You can define black and white colors in your color.xml file and add them instead using tiles[i][j].setBackgroundColor(getResources().getColor(R.color.white)); and similarly for black.
But make sure, you use a different background so they are clearly visible.
I’ve been trying to create a minesweeper game in android, and so far, all has gone accordingly. However, I’m currently stuck on the part where I have to randomly place the mines within the game board.
I’ve tried a few things that I could think of, but none of which worked, except one. However, it doesn’t give me the results that I want. Here is how I am drawing the game board (using a 2D array of buttons).
final Button currentButton = new Button(this);
final int bombState = R.drawable.bomb_state;
final Button[][] buttonArray = new Button[6][6];
final int mine = R.drawable.bomb;
final Random rand = new Random();
final int number = 36;
int button;
int row;
//create new Linear Layout
RelativeLayout linearLayout = new RelativeLayout(this);
//creating the layout Params
LayoutParams linLayoutParam = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
//set layout background
linearLayout.setBackgroundDrawable(getWallpaper());
//set LinearLayout as a root element of the screen
setContentView(linearLayout, linLayoutParam);
//create a new Table Layout for the game grid
TableLayout mineGrid = new TableLayout(this);
/*
* creates TableRows and Buttons using the for loop
* then add the buttons into the rows and the rows
* into the TableLayout
*/
for(row = 0; row < 6; row++){
//create new Table Row
TableRow currentRow = new TableRow(this);
for(button = 0; button < 6; button++){
//create new Button
for(int id = 0; id < number; id++){
currentButton.setId(id);
}
currentButton.setText(" ");
//storing the buttons into the array of Buttons
buttonArray[row][button] = currentButton;
if(currentButton.isClickable()){
currentButton.setOnClickListener(new OnClickListener() {
/*
* (non-Javadoc)
* #see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
try
{
for(int i = 0; i < 10; i++){
if(rand.nextInt(10) == i){
currentButton.setBackgroundResource(mine);
restart.setBackgroundResource(bombState);
}
}
} catch(Exception e)
{
Toast.makeText(Game.this,e.getMessage() + "Error : ",
Toast.LENGTH_SHORT).show();
}
}
});
}
//store the button into the Table Row
currentRow.addView(currentButton);
}
//add the newly created row into the table
mineGrid.addView(currentRow);
}
linearLayout.addView(score, params3);
linearLayout.addView(mineGrid, params);
}
What the above code gives me, is a 6x6 grid made up of buttons.
And the following is where I’m trying to randomly place n amount of mines within the board.
try
{
for(int i = 0; i < 10; i++){
if(rand.nextInt(10) == i){
currentButton.setBackgroundResource(mine);
restart.setBackgroundResource(bombState);
}
}
}
Unfortunately, this fills the whole board with mines, instead of only placing n amount of mine on the board. I know am missing something when I try to randomly set the mines! Can anyone advise me as to where I’m going wrong and help point me in the right direction?
Please ask me anything for clarification.
Thanks in advance.
You basically, on every click of a button try to place a mine instead placing them when you create buttons. Maybe You could add to a list, id of a buttons which are mines and only check if user has clicked on one of those buttons.
ArrayList<Integer> mines = new ArrayList<Integer>();
.
.
.
currentButton.setText(" ");
if(rand.nextInt(2)==1)
mines.add(currentButton.id);
and in onClick() You check if currentButton.id is in mines list and if it is, display appropriate image.
I'm trying to display a frame by frame animation and want to iterate through the drawables so I don't have to type all their names in case the number of frames increases.
However I can't seem to find how to iterate through the drawables. I have looked up a fair bit of java for loop tutorials but they all just printed stuff which (as far as I'm sure) don't have to use here.
Here's the relevant code (the image's names are dude1, dude2, ...):
private void startAnimation(){
animation = new AnimationDrawable();
for (int i = 1; i < 4; i++) {
animation.addFrame(getResources().getDrawable(R.drawable.dude(i)), 100);
}
animation.setOneShot(true);
ImageView imageView = (ImageView) findViewById(R.id.img);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(80, 90);
params.alignWithParent = true;
params.addRule(RelativeLayout.CENTER_IN_PARENT);
imageView.setLayoutParams(params);
imageView.setImageDrawable(animation);
imageView.post(new Starter());
}
Thx!
I think the last answer is varely true but it may be:
for (int i=0; i <10;i++){
animation.addFrame(
getResources().getDrawable(getResources().getIdentifier("dude" + i,"drawable",
getPackageName()),100);
}
Try this. getResources() needs a context.
for (int i=0;i<10;i++){
animation.addFrame(getResources().getIdentifier("dude" + i,"drawable", getPackageName()),100);
}
Here, I have assumed 10 frames (i<10).
I have used Simon's answer to iterate through my drawables that are named "c1" through "c54" and placed in an array. Here is the code I just used that works for me.
private void getDeckDrawables() {
for (int i=1; i<53; i++){
intArrDeck[i-1] = getResources().getIdentifier("c"+i,"drawable",getPackageName());
}
}
Previously, I typed them manually which took up too much room for my taste.
private void getDeckDrawables() {
intArrDeck[0]=R.drawable.c1;
intArrDeck[1]=R.drawable.c2;
intArrDeck[2]=R.drawable.c3;
}
I like to know whether there is any way by which we could get to know which image is associated with a particular imageview.
ImageView iv = new ImageView(r.drawable.pic);
If this was like this i could have know that imageview iv conatins "pic". But this is not the case in my app.
Recently i have been developing an app in which i have 26 imageview,and i use to set the images associated which each of these imageviews randomly. That is, I couldnt know predict which imageview will contain which image.
But i need to find out which image is actually associated which each imageview. I also have 26 images, one for each imageview.
How about when you set the tag to something you know:
ImageView image = (ImageView)whatever;
image.setTag("key", "Image ID");
then
String imageId = (String)imageView.getTag("key");
ImageView iv12=(ImageView)findViewById(R.id.imageView2);
ImageView iv13=(ImageView)findViewById(R.id.imageView3);
// ..............iv36.......
Random ran=new Random();
for (int i = image.length - 1; i >= 0; i--) {
int index = ran.nextInt(i + 1); // Simple swap
int a = image[index];
image[index] = image[i];
image[i] = a;
}
//..........................
final Drawable d1 = getResources().getDrawable(image[0]);
final Drawable d2 = getResources().getDrawable(image[1]);
ok
// Then I assume
iv1.setImageResource(d1); // ?
iv1.setTag("key", image[0]);