I am trying to write a program for a slide show. So far I cannot figure out how to switch between images. Every time I write a loop, the only image that shows is the last one. What am I doing wrong
P.S. I know its bad code, I am playing around with it because I am new to images for android
int currentInt;
int imgid[] = { R.drawable.better, R.drawable.beyond_innovation,
R.drawable.innovation, R.drawable.jobs, R.drawable.no_limits,
R.drawable.praxis_name, R.drawable.reinvent,
R.drawable.single_source, R.drawable.toys_to_rockets,
R.drawable.design };
RefreshHandler refreshHandler = new RefreshHandler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.slideshow);
this.txtStatus = (TextView) this.findViewById(R.id.pic_view1);
this.imageView = (ImageView) this.findViewById(R.id.slides);
for (int i = 1; i < 100000; i++) {
imageView.setImageResource(imgid[0]);
}
for (int i = 1; i < 100000; i++) {
imageView.setImageResource(imgid[1]);
}
It seems like you are putting all your images into a single ImageView and hence only the last one (which is on top) will be displayed.
If you want to make a slideshow, it is easily doable using ViewPager. I believe that's exactly the widget people want to use for displaying things using a slide show.
Related
I have created in my layout two ImageViews, let's call them imageviewTop and imageviewBottom.
I saved two images into the drawable (green_image.png and red_image.png).
I also added a button and want I would like to do is, when the button is clicked, one of the ImageViews will get selected randomly and from the green_image it will change to the red_image.
I already tried with creating a switch/case statement and generating a random number, like 1 or 2.
Based on this number the case statement would update either the top or bottom image.
This is working fine for 2 ImageViews, but in case I would have 100, I would need to create 100 cases in code.
I am searching for a more dynamic option.
I know how to update the image for the ImageView, I am struggling with the part, on how to select one ImageView randomly, if it is possible.
Here is the code:
public class MainActivity extends Activity {
ImageView imagevieTop, imageviewBottom;
Button randomButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagevieTop = (ImageView) findViewById(R.id.imageViewTop);
imageviewBottom = (ImageView) findViewById(R.id.imageViewBottom);
randomButton = (Button) findViewById(R.id.buttonRandom);
randomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// randomly select one of the two imageviews
// for example: randomly selected imageviewTop
// set imageresource red_image to imageviewTop
//at next start up it would select either top or bottom, 50%-50% and then assign the image to it
}
});
}
}
You could just use one ImageView, and randomize the picture you draw.
Alternatively, you could adjust this to use an array of ImageViews. Your choice.
The line you want, though, is int index = random.nextInt(imgs.length); to get a random index from the list.
public class MainActivity extends Activity {
int[] imgs = new int[] { R.drawable.green_image, R.drawable.red_image };
Button randomButton;
private final Random random = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imgView = (ImageView) findViewById(R.id.imageView);
randomButton = (Button) findViewById(R.id.buttonRandom);
randomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index = random.nextInt(imgs.length);
// randomly select one of the two drawables
int resId = imgs[index];
// set imageresource imgView
Drawable d = getResources().getDrawable(resId);
imgView.setImageDrawable(d);
}
});
}
}
To handle the "100 ImageViews" problem, I'd recommend not copying 100 lines of code, and instead looping over reasonable ID values.
List<ImageView> imgViews = new ArrayList<ImageView>();
for (int i = 0; i < 100; i++) {
int resId = getResources().getIdentifier("imgView" + i, "id", getPackageName());
ImageView nextImg = (ImageView) findViewById(resId);
imgViews.add(nextImg);
}
In case you want to do a dynamic selection of "n" ImageView elements, then you'll need to store them in a data structure (e.g. an array, a list, etc.). For example this code will select a random ImageView from a list:
public ImageView getRandomImageView(final List<ImageView> imageViewList) {
final Random random = new Random();
//The "nextInt" method works in the half-open range [0, n), so it'll never be equal to the list size.
final int randomElement = random.nextInt(imageViewList.size());
return imageViewList.get(randomElement);
}
In your case, with two ImageView's ("imagevieTop" and "imageviewBottom") declared in fixed variables then you would need to pass them to a list or something similar in order to select one of them dynamically.
hows it going? I'm creating a little training app for a project, its going fine except for a formatting problem im getting. So, ive a csv file with a name and age for a client. an array is created from this, then I've got a scroll View containing a grid layout and i create Image Buttons from the client array. that's all fine. ive got an add client button at the end of this, the button and its activity work fine, but when you come back to the main screen, the buttons are all screwed up (huge, misplaced etc). So i figured i would loop through and delete all the buttons and repopulate the main screen, except, since i programmatically created them, i cant figure out how to find them to delete them. i tried setting their id's to the index of the array, but then i get a null pointer error.
Function where the buttons are created:
public void fillActivity_main(){
if(listPopulated == false) { // check to see if its aready been created
populateClientList();//fill array with client objects
listPopulated = true;
}
//setup asset manager
AssetManager am = getApplicationContext().getAssets();
//Create the "GridLayout Image Board"
GridLayout buttonBoard = (GridLayout) findViewById(R.id.buttonboard);
int idealWidth = buttonBoard.getWidth(); //get width of the board
int idealHeight = buttonBoard.getHeight() / 2;//same
//create the Listeners, this is a place holder for now but will eventually use SetCurrentClient() (or maybe just switch to Start screen, with the current client?)
View.OnClickListener imageClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("CLICK AT: " + v.getId());
Client temp = clientList[v.getId()];
Intent i = new Intent(getApplicationContext(), DisplayClient.class);
System.out.println(temp.getName());
i.putExtra("name", temp.getName());
System.out.println(i.getStringExtra("name"));
i.putExtra("age", Integer.toString(temp.getAge()));
startActivity(i);
}
};
int j = 0; //used the keep track of the id's we set for the buttons
for (int i = 0; i < clientList.length; i++) {
if (clientList[i] != null) {
//creation and ID setting
ImageButton imgbutton = (ImageButton) new ImageButton(this);
imgbutton.setId(i);
//Layout shit
imgbutton.setImageResource(R.mipmap.ic_launcher);
imgbutton.setMinimumWidth(idealWidth);
imgbutton.setMinimumHeight(idealHeight);
imgbutton.setOnClickListener(imageClickListener);
//check and set image
if(clientList[i].getClientImage().equals(" ")) {
try{
imgbutton.set(am.openFd(clientList[i].getClientImage()));}
catch(Exception ex){
ex.toString();
}
Log.d("ClientImageCheck", "No picture found for " + clientList[i].getName());
}
buttonBoard.addView(imgbutton);
j++;
}
}
//create the new Client Button at the end of all the rest.
Button newClientButton = (Button) new Button(this);
newClientButton.setText("+"); // obvious
newClientButton.setLayoutParams(new LinearLayout.LayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT));
newClientButton.setWidth(idealWidth);
newClientButton.setHeight(idealHeight);
View.OnClickListener newClientListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), CreateClientForm.class);
startActivityForResult(i, 199);
//System.out.println("Doing good so far, leaving the createclient form bnut still in main");
}
}; // create listener
newClientButton.setOnClickListener(newClientListener); // assign listener
buttonBoard.addView(newClientButton); //add the button the buttonBoard, after all the clients have been added
}
Function where i do the deleting:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check which request we're responding to
if (requestCode == 199) {
// Make sure request was successful
if (resultCode == RESULT_OK) {
// The user made a name and crap.
Bundle extras = data.getExtras();
String name = extras.getString("name");
int age = extras.getInt("age");
Client temp = new Client(name, age);
addClientToArray(temp);
System.out.println(name + "attempted add to array");
}
for(int i = 0; i<clientList.length; i++ ){
View v = findViewById(i);
((ViewManager) v.getParent()).removeView(v);
}
fillActivityMain();
}
if i've got the logic right, the 'i' in the loop should be the appropriate id. Granted, the teach has kind of thrown us in the deep end for this project, never taken mobile apps or anything, so all this code is the result of me googling issues as i run into them. I've read the basics for Views, intents, etc, but there must be something i'm missing.
I've tried making the gridLayout that the buttons sit on a class variable so i could call it buttonBoard.removeView(i) or something.
ive also tried `
for(int i = 0; i<clientList.length; i++ ){
ImageButton btn = (ImageButton) findViewByid(i);
((ViewManager) v.getParent()).removeView(btn);
}
Can you add the replacement images at the same time that you delete the existing images? If so, try this:
for(int i = 0; i < buttonBoard.getChildCount(); i++) {
ImageButton tempButton = (ImageButton) buttonBoard.getChildAt(i);
tempButton.setVisibility(View.INVISIBLE);
buttonBoard.addView(yourImageButtonHere, i); //adds a new ImageButton in the same cell you are removing the old button from
buttonBoard.removeView(tempButton);
}
This approach should also prevent the GridLayout from rearranging where the children are. I believe the default behavior if you delete a child view is that the GridLayout will re-order the children so there is not empty cell at the beginning of the grid. I hope that makes sense.
There is so much wrong with this approach.
Mainly you don't have to create the ImageButtons manually and add them to the GridLayout. That is what recycled views such as GridView or RecyclerView are for. In fact you should use those to avoid OutOfMemoryError from having too much images in your layout.
But also you cannot just call setId(i) in the for loop. Android holds many ids already assigned and you can never be sure whether the id is safe. (Unless you use View.generatViewId())
And since you only want to remove all views added to your GridLayout why don't you just call removeAllViews() on the buttonBoard?
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.
I want to store drawable images in a 2D array
ImageView iv1[][] = new ImageView[2][20];
int mylist[][]={{R.drawable.step_000,R.drawable.step_001,R.drawable.step_002,R.drawable.step_003,R.drawable.step_004,
R.drawable.step_005,R.drawable.step_006,R.drawable.step_007,R.drawable.step_008,R.drawable.step_009,R.drawable.step_010,
R.drawable.step_011,R.drawable.step_012,R.drawable.step_013,R.drawable.step_014,R.drawable.step_015,R.drawable.step_016,
R.drawable.step_017,R.drawable.step_018,R.drawable.step_019},
{R.drawable.step_100,R.drawable.step_101,R.drawable.step_102,R.drawable.step_103,R.drawable.step_104,
R.drawable.step_105,R.drawable.step_106,R.drawable.step_107,R.drawable.step_108,R.drawable.step_109,R.drawable.step_110,
R.drawable.step_111,R.drawable.step_112,R.drawable.step_113,R.drawable.step_114,R.drawable.step_115,R.drawable.step_116,
R.drawable.step_117,R.drawable.step_118,R.drawable.step_119}};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
iv=(ImageView)findViewById(R.id.imageView1);
iv2=(ImageView)findViewById(R.id.left);
iv3=(ImageView)findViewById(R.id.right);
iv2.setVisibility(View.INVISIBLE);
Bundle bundle=getIntent().getExtras();
String value=bundle.getString("key");
int step = getIntent().getExtras().getInt("steps");
Toast.makeText(getApplicationContext(), ""+step,Toast.LENGTH_SHORT).show();
int a;
a=step;
for(int i=0;i<20;i++)
{
for(int j=0; j<a; j++)
iv1[i][j] = (ImageView)findViewById(mylist[i][j]);
}
if(value.contentEquals("cristiano"))
{
iv.setImageResource(mylist[i][j]);
}
It appears that you are setting everything in the iv1 ImageView array correctly, using the two for loops. The problem is that you are setting one ImageView on the screen to the entire array, so it is only going to show one. You should try doing a GridLayout of multiple ImageViews and then setting each of those one by one. I know it would be convenient to do it this way, but I don't think there is a way to make it work like that. In addition, I would think that iv.setImageResource(mylist[i][j]); would give you trouble as it is outside the loop and does not know what i or j are.
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.