public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1;
final ImageView image;
button1 = (Button) findViewById(R.id.button1);
image = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for (int j = 1; j < 6; j++) {
Drawable dreaw = getResources().getDrawable(getResources().getIdentifier("d002_p00"+j, "dreaw",getPackageName()));
image.setBackgroundResource("R.drawable." +dreaw);
}
}
});
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
i am new in android i want to change my image when i pressed my button image
in this line image.setBackgroundResource("R.drawable." +dreaw); it shows error how i can fix it please help me.
You can't do that :
Drawable dreaw = getResources().getDrawable(getResources().getIdentifier("d002_p00"+j, "dreaw",getPackageName()));
image.setBackgroundResource("R.drawable." +dreaw);
Try :
Drawable dreaw = getResources().getDrawable(getResources().getIdentifier("d002_p00"+j, "dreaw",getPackageName()));
image.setBackground(dreaw);
R.drawable.xxx is not a string it is a auto genarated intiger id for each resources.
image.setBackgroundResource("R.drawable." +dreaw);is wrong.
you can do onething
int res=getResources().getIdentifier("d002_p00"+j, "drawable",getPackageName()));
image.setBackgroundResource(res);
Try this
image.setBackgroundDrawable(dreaw);
This method is deprecated from api level 16 but fro backword compatibility you should use above method.
Just do:
image.setBackgroundDrawable(drew);
As your comment quotes "it worked bt it showa my first and last image."
You can only see the first and last image.Because the for loop is in a hurry burry,that means you can't see the changing of image,because the for loop is executed within ms(Milli or Micro Seconds).So you want to put this
Thread.sleep(<put_how_much_ms_you_want_to_make_the_for_loop_sleep);
to sleep the for loop time to time.If you put this
Thread.sleep(1000);//Make the thread or program blocked for 1 second.
For implementing in your For loop you can change your For loop like this.
for (int j = 1; j < 6; j++)
{
int res=getResources().getIdentifier("d002_p00"+j, "drawable",getPackageName()));
image.setBackgroundResource(res);
Thread.sleep(1000);//Make the for loop wait for 1 second.
}
By this you can see the transition of images.
May i know it helps you or not.
Related
I created array of buttons in a loop. It seems to work, but if I add OnClickListener to each button, I get a NullPointerException. How do I fix that?
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
fieldModel=new Field();
buttons=new Button[10][10];
for(int i=0; i<10; i++) {
for (int j = 0; j < 10; j++) {
String buttonID = "button" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(new View.OnClickListener() { // <-- I get the exception here...
#Override
public void onClick(View v) {
"some action"
}
});
In R.layout.main_layout, are there 100 buttons named 'button00' to 'button99'? if any one is missing, it will result in a null pointer at the line you have marked.
It would also be worth looking at using a GridView, or a RecyclerView with GridLayoutManager, instead of adding the buttons manually - if it would suit your app.
You get the exception because the id isn't contained by the activity layout. You have to add them first in the layout file if you want to match the Button object through findViewById or, if you have them already, make sure the Id you use in findViewById (resId) is correct.
I have a grid with 12 buttons and I want animate this buttons. I have them in a vector and when I intend execute ".startAnimation" always I have "NullPointer" exception and I don't know why.
I have this:
final private int tamGrid=12;
private Button[] botones = new Button[tamGrid];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego_grid12);
loopAnimation=AnimationUtils.loadAnimation(this, R.anim.animacionbotongrid12);
//Asociamos los elementos de la vista:
asociateElements();
}
public void asociateElements(){
String buttonID;
int resID;
for(int i=0; i<tamGrid; i++) {
buttonID="boton"+Integer.toString(i);
resID = getResources().getIdentifier(buttonID, "id","butterflydevs.brainstudio");
buttons[i]=(Button)findViewById(resID);
buttons[i].startAnimation(loopAnimation);
}
}
Why don't work this? The error is
Caused by: java.lang.NullPointerException
in the line of startAnimation.
I've noticed that happens also when i try this:
botones[0].setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//Acciones del botón:
botones[0].setBackgroundColor(Color.RED);
}
}
);
When I use a index in "botones[n]".
It also has this happened to anyone?
I suggest that you put the loop inside onStart() callback. Maybe your buttons have not yet been created at that point in your code.
I found the problem myself, one button was named wrong, and therefore when I through the vector, this cause a Null Pointer Exception.
for(int i=0; i<gridSize; i++)
buttons[i].startAnimation(animation);
for(int i=0; i<gridSize; i++) {
buttonID="button"+Integer.toString(i);
resID = getResources().getIdentifier(buttonID, "id","package.name");
buttons[i]=(Button)findViewById(resID);
}
Work with buttons in loops works perfectly. Thanks for all.
I'm writing an app that needs 86 small, square buttons in one layout - 6 columns preferably. I want to reference the buttons to show a different image depending on the button pressed. I coded it the hard way using a relative layout> scrollview (in XML), then 86 individual buttons, but it seemed like an amateur solution.
Can someone show me how to code an array of identical buttons with different id's directly within the Java class the right way? (By the way, i have tried hard to find this answer with Google, but when i search variations of this question i always get tutorials about JButtons, which i believe can't be used in an android app).
Thanks in advance.
This may help
public class Test extends Activity{
List<Button> buttonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
Button doneButton=(Button)findViewById(R.id.your_final_button);
ScrollView view=(ScrollView)findViewById(R.id.your_scroll_view);
view.addView(tableLayout(20));//20 rows
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(Button b : buttonList){
b.getText();//whatever you wanna do
}
}
});
}
private TableLayout tableLayout(int count) {
TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
tableLayout.setBackgroundColor(Color.WHITE);
int noOfRows = count ;
for (int i = 0; i < (noOfRows+1); i++) {
int rowId = 3 * i;
tableLayout.addView(createOneFullRow(rowId));
}
return tableLayout;
}
private TableRow createOneFullRow(int rowId) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
//6 columns
tableRow.addView(createButton("text1"));
tableRow.addView(createButton("text2"));
tableRow.addView(createButton("text3"));
tableRow.addView(createButton("text4"));
tableRow.addView(createButton("text5"));
tableRow.addView(createButton("text6"));
return tableRow;
}
private View createButton(String string) {
// TODO Auto-generated method stub
Button button = new Button(this);
button.setText(string);
buttonList.add(button);
return button;
}
}
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1;
final ImageView image;
button1 = (Button) findViewById(R.id.button1);
image = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int j=0;
while(j<=4){
int res=getResources().getIdentifier("d002_p00"+j,"drawable",getPackageName());
image.setBackgroundResource(res);
j = j+1;
}
}
});
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
}
}
I have 3 questions:
What is wrong with this code this code only show 1st and last image? how I can fix it?
I don't want to rotate my apps. How I can do that?
How I can mentioned a user in Stack Vverflow? I tried #username but it didn't work.
Answer for question 1: What is wrong with this code this code only show 1st and last image? how I can fix it?
Put the int j outside the onClick and change the while to an if
int j=0;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(j >= 0 && j <= 4){
int res = getResources().getIdentifier("d002_p00"+j, "drawable", getPackageName());
image.setBackgroundResource(res);
j++;
}
}
});
Answer for question 2: I don't want to rotate my apps. How I can do that?
See this answer of another stackoverflow question.
Answer for question 3: How I can mentioned a user in Stack Vverflow? I tried #username but it didn't work.
I don't know for sure myself, but I think you can't use #user_name to reply a comment when there is only one commenter apart from yourself (at least I couldn't). If you want to credit someone however, I would suggest putting their profile-page in a link like so: #user3546792 (Click their name, copy the link, click the Add Hyperlink-button in SO and paste the copied link. Then change [enter link description here] to [#user_name]
For question 2:
I don't want to rotate my apps. How I can do that?
Your just add this in your android Manifest:
android:orientation="portrait"
Android - get resources from XML
Hi,
I am developing an android app for a quiz game, the game has 24 questions, and each question has a String(question) and four ImageButton(answer), when user select the correctImageButton`, then they go to next question.
But the problem is, after selecting the first correct answer, the screen refreshes with a new question and a new set of images, but it freezes there, and no matter what I click, it will not go to next question. I have attached my code and any help appreciated!!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_game);
// set variables
int fourImageId[] = { R.id.1_4a, R.id.1_4b,R.id.1_4c, R.id.1_4d };
questionText = (TextView) findViewById(R.id.question1);
questionList = getResources().getStringArray(R.array.question);
correctAnswerIdList = ListOfImages.getListOfCorrectImages();
imageIdList = ListOfImages.getListOfImages(); //two dimension array
// give values to four image buttons
for (int i = 0; i < 4; i++) {
fourImages[i] = (ImageButton) findViewById(fourImageId[i]);
final int temp = fourImageId[i];
fourImages[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (temp==correctAnswerIdList[index]){
questionText.setText(questionList[index]);
for (int i = 0; i < imageIdList[index].length; i++) {
fourImages[i].setImageResource(imageIdList[index][i]);}
index++;
}
}
});}
Your temp variable never changes after all the button click listeners are set. Because of this, the if (temp==correctAnswerIdList[index]) statement will only successfully execute once.
Your for (int i = 0; i < 4; i++) statement needs to execute once for each new question. Right now it only executes once, sets up the new question and image buttons, but your app doesn't know where to go from there.