In my Android app i click on the "random" button and the app shows me a random xml file out of first.xml, second.xml or third.xml. This works all fine but i wondered if there is an easier or a nicer way to implement it if you have 100+ xml files.
I found some code (which works fine) which shows random ImageViews:
private Integer [] mImageIds = {
R.drawable.one,
R.drawable.two,
R.drawable.three,
};
private static final Random rgenerator = new Random();
private ImageView iv;
.
.
.
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv = (ImageView) findViewById(R.id.imageviewyeah);
iv.setImageResource(q);
This is how my main.xml looks:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button
android:id="#+id/first_button"
android:onClick="change"
android:text="first"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/second_button"
android:onClick="change"
android:text="second"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/third_button"
android:onClick="change"
android:text="third"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/random_button"
android:onClick="change"
android:text="random"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
and this is the code which is processed when you click on a button:
package com.random;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void change(final View view){
switch (view.getId()) {
case R.id.first_button:
startActivity(new Intent(this, FirstPage.class));
break;
case R.id.second_button:
startActivity(new Intent(this, SecondPage.class));
break;
case R.id.third_button:
startActivity(new Intent(this, ThirdPage.class));
break;
case R.id.random_button:
Random random = new java.util.Random();
int rand = random.nextInt(3);
switch (rand) {
case 0:
startActivity(new Intent(this, FirstPage.class));
break;
case 1:
startActivity(new Intent(this, SecondPage.class));
break;
case 2:
startActivity(new Intent(this, ThirdPage.class));
break;
}
}
}
}
Any help is much appreciated!
Now I've got a fairly similar question. So far i implemented a "Random"-button. If you click on it a random xml-file will be shown. Note: The content (TextViews, ImageViews) are different in the xml-files but the java code (clicking on buttons etc.) is the same!
That's the code if you click on the "Random"-button:
switch (view.getId()) {
case R.id.first_button:
startActivity(new Intent(this, FirstPage.class));
break;
case R.id.second_button:
startActivity(new Intent(this, SecondPage.class));
break;
case R.id.third_button:
startActivity(new Intent(this, ThirdPage.class));
break;
case R.id.random_button:
Intent intent = new Intent(this, DisplayRandomPage.class);
startActivity(intent);
and this is in the DisplayRandomPage.class
public class DisplayRandomPage extends Activity {
private Integer [] mLinearLayoutIds = {
R.layout.one
R.layout.two,
R.layout.three
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Random random = new java.util.Random();
int rand = random.nextInt(3);
setContentView(mLinearLayoutIds[rand]);
}
}
What i'd like to do is creating a DisplaySpecificPage.class. Above I've shown my main.class with the switch-case-clause. So when i click on the first button, it will start the FirstPage.class, clicking the second, it will start SecondPage.class, and so on. So for each xml-file i have to create a new java-class although the different java-classes do all the same. Only the xml-files are different. So i'd like to put something like this:
pseudo-code:
case R.id.first_button:
startActivity(new Intent(this, DisplaySpecificPage.class)) with R.layout.first_page;
break;
how do i pass the ID from the layout (R.layout.first_page) on?
If your classes all do the same thing except have a different layout called, you could create a single display class
public class DisplayPage extends Activity
and send it the id of the layout in the intent extras.
You can get the id by doing something like
Class c = Class.forName("com.random.R$layout");
Integer iLayout = new Integer(c.getField("layout"+rand).getInt(new R.layout()));
(assuming your layouts are called layout1.xml, layout2.xml etc.)
Send it to your DisplayPage,
Intent intent = new Intent(this, DisplayPage.class);
intent.putExtra("Layout", iLayout);
startActivity(intent);
and get it back by doing something like
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// default value
int iLayout = R.id.main;
if (savedInstanceState != null)
{
iLayout = savedInstanceState.getInt("Layout");
}
else
{
Bundle extras = getIntent().getExtras();
if (extras != null)
{
iLayout = extras.getInt("Layout");
}
}
setContentView(iLayout);
}
You'll also want to override onSaveInstanceState to include that int so that, e.g., changing the screen orientation doesn't make it forget what it was showing.
try
{
Class c = Class.forName("com.random.R$layout");
Field[] aFields = c.getFields();
Random random = new Random();
boolean isUsableLayout = false;
Integer iLayout = 0;
while (!isUsableLayout)
{
int rand = random.nextInt(aFields.length);
iLayout = new Integer(c.getField(aFields[rand].getName()).getInt(new R.layout()));
if (iLayout != R.layout.main)
{
isUsableLayout = true;
}
}
Intent intent = new Intent(this, DisplayPage.class);
intent.putExtra("Layout", iLayout);
startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
Related
I have a button inside a view that checks some constraints, and then starts another activity, however the startActivity() call does not do anything, the new activity's onCreate() never gets called, and the code then continues past it. I have checked using logging and breakpoints, and the conditions are being met and startActivity() is being called. Both activities are defined in the application manifest.
From the source activity's onCreate():
int[] winning_player;
int next_player;
int[] scores;
[...]
final Button end_turn_button = (Button) findViewById(R.id.end_turn);
end_turn_button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (winning_player[0] == next_player) {
Intent intent = new Intent(getApplicationContext(), FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
});
FinalScreenActivity.java
public class FinalScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_screen);
Intent intent = getIntent();
final int[] scores = intent.getIntArrayExtra("SCORES");
// put the scoreboard in ascending order
Arrays.sort(scores);
// find the scoreboard in the view
TableLayout scoreboard = (TableLayout) findViewById(R.id.scoreboard);
// get the string resources to be formatted
Resources res = getResources();
String player_name_format = res.getString(R.string.player);
// Set the scoreboard in the view
Log.d("brains.PlayActivity", "onCreate: Creating scoreboard");
// for each player entry in the scoreboard
for (int i = 0; i < scores.length; i++) {
Log.d("brains.PlayActivity", "onCreate: adding scoreboard entry "+String.valueOf(i));
// create 2 TextViews
TextView player_name = new TextView(FinalScreenActivity.this);
TextView player_score = new TextView(FinalScreenActivity.this);
// Set the size of the TextViews
player_name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
// set the first one to the player's name string resource
player_name.setText(String.format(player_name_format, i + 1));
// set the second one to the player's score resource, which takes the score twice (once for the number itself, and once to work out which plural is needed)
player_score.setText(res.getQuantityString(R.plurals.brains, scores[i], scores[i]));
// Create a TableRow to put the score into
TableRow scoreboard_entry = new TableRow(FinalScreenActivity.this);
// Set the size of the TableRow
scoreboard_entry.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
// Add the TextViews to the TableRow
scoreboard_entry.addView(player_name);
scoreboard_entry.addView(player_score);
// Add the TableRow to the TableLayout
scoreboard.addView(scoreboard_entry);
}
// Get the title text
TextView title_text = (TextView) findViewById(R.id.title_text);
title_text.setText(res.getQuantityString(R.plurals.win_brains, scores[scores.length - 1], scores.length - 1, scores[scores.length - 1]));
// set the play again button
Button play_again_button = (Button) findViewById(R.id.play_again_button);
play_again_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), SelectPlayersActivity.class);
startActivity(intent);
}
});
}
}
and activity_final_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="uk.co.bluesapphiremedia.android.zombiedice.FinalScreenActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/scoreboard"
android:layout_below="#+id/title_text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_again"
android:id="#+id/play_again_button"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
end_turn_button.setOnClickListener(this);
//override onClick() method in activity implement interface View.OnClickListner
public void onClick(View v) {
if(v.getId() == R.id.end_turn){
if (winning_player[0] == next_player) {
Intent intent = new Intent(this,FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
}
This question already has answers here:
Multiple Buttons' OnClickListener() android
(11 answers)
Closed 7 years ago.
When you have many buttons in a view and all the button have listener. Your main activity gets dirty.
Anyone know how to organize listeners ?
Currently I used this way and implement onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
You could set the property:
android:onClick="buttonClicked"
in the xml file for each of those buttons, and use this in the java code:
public void buttonClicked(View view) {
if (view.getId() == R.id.button1) {
// button1 action
} else if (view.getId() == R.id.button2) {
//button2 action
} else if (view.getId() == R.id.button3){
//button3 action
}
}
You can implement onclicklistner for multiple buttons using swith case
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.firstButton:
// do your code
break;
case R.id.secButton:
// do your code
break;
case R.id.thirdButton:
// do your code
break;
......
default:
break;
}
}
Ya...It s the best way to use multiple onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
#Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.spotifyBtn:
intent = new Intent(this, SimpleSingleExample.class);
break;
case R.id.superDuoBtn:
intent = new Intent(this, CustomExample.class);
break;
case R.id.libraryBtn:
intent = new Intent(this, SequenceExample.class);
break;
case R.id.buildItBiggerBtn:
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
break;
}
if(intent!=null){
startActivity(intent);
}
}
If you want better way than you have to use Android Annotations, its simple and useful, you can find here
Add those View object references to some type of list, iterate through it usin a for-each loop, then call the setOnClickListener on each element which will reduce those lines to just 2 lines for you.
ArrayList <View> list = new ArrayList <>(spotify,superDuoBtn,libraryBtn, buildBiggerBtn, capstoneBtn);
for (View view : list) {
view.setOnClickListener(this);
}
The most obvious example of alternative approaches to solving a single problem seems to be the various ways you can handle button clicks. As far as I know, there are four different ways to add listeners for handling button clicks. If you know of other ways, please post a comment and share them with us.
Xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Inner Class (btn1)" android:id="#+id/Button01"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>
<Button android:text="Anonymous Inner Class (btn2)"
android:id="#+id/Button02" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Implementing an Interface (btn3)"
android:id="#+id/Button03" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Calling From XML Layout (btn4)"
android:id="#+id/Button04" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="btn4Listener">
</Button>
</LinearLayout>
in MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//method 1 - uses an inner class named btn1Listener...
Button btn1 = (Button)findViewById(R.id.Button01);
btn1.setOnClickListener(btn1Listener);
//method 2 - use an anonymous inner class as a listener...
Button btn2 = (Button)findViewById(R.id.Button02);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn2 - uses an anonymouse inner class");
}
});
//method 3 - note that this class implements
//the View.OnClickListener interface
//which means that we must implement the onClick()
//method (which you'll find below)..
Button btn3 = (Button)findViewById(R.id.Button03);
btn3.setOnClickListener(this);
//method 4 - look at the method btn4Listener() below
}
//here's the inner class used as a listener for btn1...
private View.OnClickListener btn1Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn1 - uses an inner class named btn1Listener");
}
};
//here's a method that you must have when your activity implements the
//View.OnClickListener interface...
#Override
public void onClick(View v) {
showToastMessage("you clicked on a btn3, which uses this Activity as the listener");
}
//here's the handler for btn4 (declared in the xml layout file)...
//note: this method only works with android 2.1 (api level 7), it must be public and
//must take a single parameter which is a View
public void btn4Listener(View v) {
showToastMessage("You clicked btn4 - listener was set up in the XML layout");
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
I have looked at every example of switching between activities and I always get the same result. The app bombs.
As far as I can tell if you have a java class that populates the content of a layout then in order to switch to the other layout, you must 'link' to the java file which in turn will open the setContentView(R.layout.whatever);
When I try to do this, like I say my app bombs out. My code is as follows:-
FROM Java class:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.goesnews);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), ac2.class);
startActivityForResult(myIntent, 0);
}
});
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
}
TO java file (ac2)
public class ac2 extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
}}
Can anyone help out here?
Try to remove the zero from this line:
startActivityForResult(myIntent, 0);
like this and change it to just:
startActivity(myIntent);
and change this line:
Intent myIntent = new Intent(view.getContext(), ac2.class);
To this:
Intent myIntent = new Intent(firstActivityName.this, ac2.class);
because you are getting here the context of the button and not of the activity.
The solution was simple and was based on the response from VSK (Thanks) with a little tweak.
The ImageButton required :-
<Button
android:id="#+id/previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click"
android:onClick="move" />
Java required:-
public void move(View v)
{
Intent myIntent = new Intent(yourclass.this, ac2.class);
startActivityForResult(myIntent, 0);
}
VSK - please note '0' attribute of startActivityForResult
Thanks all
try this way
add onclick function to your button in xml file
like this
<Button
android:id="#+id/previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click"
android:onClick="move" />
and in ur java file
make a function move like this
public void move(View v)
{
Intent myIntent = new Intent(yourclass.this, ac2.class);
startActivityForResult(myIntent,0);
}
I want to know how I can obtain the value of a button and then use it on another activity to display content accordingly.
Example:
I have 3 buttons Image1, Image2 & Image3 on my MainActivity.
Now based on what button the user clicks (Image1, Image2 & Image3), a corresponding image is displayed on a new activity.
I know how to create these buttons, the new activity and also how to display an image on the new activity. How do I display the image based on what button the user clicks?
Your class should implement OnClickListener and override onClick()
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
button1.setOnClickListener(new OnClickListener(this));
button2.setOnClickListener(new OnClickListener(this));
button3.setOnClickListener(new OnClickListener(this));
#Override
public void onClick(View v){
switch(v.getId()) //get the id which is an int
{
case R.id.button1 : //if its button1 that is clicked
Intent i= new Intent("com.example.secondActivity");
i.puExtra("key",value);
startActivity(i);
// use intents to pass information to secondActivity and display the image there
break;
case R.id.button2 :
Intent i= new Intent("com.example.secondActivity");
startActivity(i)
//use intents to pass information to secondActivity and display the image there
break;
case R.id.button3 :
Intent i= new Intent("com.example.secondActivityy");
startActivity(i)
//use intents to pass information to secondActivity and display the image there
break;
}
}
To pass values using intents
On Button click
Intent i= new Intent("com.example.secondActivity");
i.puExtra("key",value);
startActivity(i);
In Second Activity retrieve it as below
Bundle extras = getIntent().getExtras();
if(extras!=null)
{
int values= extras.getInt("key");
}
Why not use a switch case to determine which button was clicked by the user and show the corresponding / relevant image in the next activity? For example:
First, make your Activity implement the OnClickListener. Then, in the onCreate() cast your Buttons and set their setOnClickListener
#Override
public void onCreate(Bundle savedInstanceState) {
....
Button Image1 = (Button) findViewById(R.id.Image1);
Image1.setOnClickListener(this);
.... // THE REST OF THE BUTTONS
}
I am assuming you are passing a Bundle in the Intent for starting the next Activity. Change that code to pass information that contains which button was pressed.
For example:
Intent showPhoto = new Intent(CurrentActivity.this, YOUR_SECOND_ACTIVITY.class);
showPhoto.putExtra("BUTTON_CLICKED", "IMAGE1");
startActivity(showPhoto);
#Override
public void onClick(View v) {
// Perform action on click
switch(v.getId()) {
case R.id.Image1:
// RUN THE CODE TO START THE NEXT ACTIVITY
Intent showPhoto = new Intent(CurrentActivity.this, YOUR_SECOND_ACTIVITY.class);
showPhoto.putExtra("BUTTON_CLICKED", "IMAGE1");
startActivity(showPhoto);
break;
case R.id.Image2:
// RUN THE CODE TO START THE NEXT ACTIVITY
Intent showPhoto = new Intent(CurrentActivity.this, YOUR_SECOND_ACTIVITY.class);
showPhoto.putExtra("BUTTON_CLICKED", "IMAGE2");
startActivity(showPhoto);
break;
case R.id.Image3:
// RUN THE CODE TO START THE NEXT ACTIVITY
Intent showPhoto = new Intent(CurrentActivity.this, YOUR_SECOND_ACTIVITY.class);
showPhoto.putExtra("BUTTON_CLICKED", "IMAGE3");
startActivity(showPhoto);
break;
}
}
}
I have 3 buttons Image1, Image2 & Image3 on my MainActivity. Now based
on what button the user clicks (Image1, Image2 & Image3), a
corresponding image is displayed on a new activity.
=> As you already said yo know how to create buttons and initiate it.
Now you just need to assign OnClickListener to every buttons and then pass Image id or URL into the Intent by which you are calling new activity.
Check the code posted by #IceMAN above, now as I mentioned above, put ImageURL or Image ID into Intent by using putExtra() method.
For example:
Intent intent= new Intent(CurrentClass.this, ImageActivity.class);
intent.putExtra("ImageURL",strImageURL);
startActivity(i);
For example you have 3 Buttons and ImageView in Main layout:
Main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:id="#+id/btn1"
android:text="button 1"
/>
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:id="#+id/btn2"
android:text="button 2"
/>
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:id="#+id/btn3"
android:text="button 3"
/>
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/iv"
/>
I your activity metod onClick handle events from three buttons. And we need to recognize that the button has been pressed.
MyActivity.java
public class MyActivity extends Activity implements View.OnClickListener {
Button btn1;
Button btn2;
Button btn3;
ImageView iv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn1);
btn3 = (Button) findViewById(R.id.btn1);
iv = (ImageView) findViewById(R.id.iv);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn1:
{
Toast toast = Toast.makeText(this, "onClickButton1", Toast.LENGTH_SHORT);
toast.show();
iv.setImageDrawable(R.drawable.my_image_1);
break;
}
case R.id.btn2:
{
Toast toast = Toast.makeText(this, "onClickButton2", Toast.LENGTH_SHORT);
toast.show();
iv.setImageDrawable(R.drawable.my_image_2);
break;
}
case R.id.btn3:
{
Toast toast = Toast.makeText(this, "onClickButton3", Toast.LENGTH_SHORT);
toast.show();
iv.setImageDrawable(R.drawable.my_image_3);
break;
}
}
}
}
Where my_image_1, my_image_2, my_image_3 - images, from your Drawable folder.
Hope its Help.
Add this in onCreate of your activity that contains the 3 buttons
Button image1 = (Button) findViewById(R.id.image1);
image1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), DisplayImagActivity.class)
.putExtra("ImageName", "Image1"));
}
});
Button image2 = (Button) findViewById(R.id.image2);
image2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), DisplayImagActivity.class)
.putExtra("ImageName", "Image2"));
}
});
Button image3 = (Button) findViewById(R.id.image3);
image3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), DisplayImagActivity.class)
.putExtra("ImageName", "Image3"));
}
});
Add this in onCreate of your activity where you will set the image:
String imageName = getIntent().getStringExtra("ImageName");
if(imageName.equals("Image1")) {
//set image 1
}
else if(imageName.equals("Image2")) {
//set image 2
}
else if(imageName.equals("Image3")) {
//set image 3
}
You simply implement one ClickListener for each button, which will start the corresponding activity. See an example here.
I know this is and old question, but there is another way, which I prefer, because you can use the same default method for all buttons.
First add a tag to each button.
<Button
android:id="#+id/imageOneButton"
android:tag="1"
android:onClick="chooseImage" />
Then use this tag number to alter the behavior of your method.
public void chooseImage(View view) {
int imageNumber = Integer.parseInt(view.getTag().toString());
// I'll just send this tag number to a toast, but you can send it in your intent
// as an "Extra"
Toast.makeText(this, view.getTag().toString(), Toast.LENGTH_SHORT).show();
}
My code is this:
public class startgame extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
final Random rgenerator = new Random();
//setup the questions
List<String> questions1 = new ArrayList<String>();
questions1.add("Who is the actual CEO at Apple?");
questions1.add("Who is the actual CEO at Microsoft?");
questions1.add("Android is made by:");
String thequestion = questions1.get(rgenerator.nextInt(questions1.size()));
TextView question = (TextView)findViewById(R.id.textView1);
question.setText(thequestion);
questions1.remove(thequestion);
//Initialise the button variables
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
if (thequestion.equals("Who is the actual CEO at Apple?")) {
List<String> questions1res = new ArrayList<String>();
questions1res.add("Steve Jobs");
questions1res.add("Steven Sinofsky");
questions1res.add("Tim Cook");
questions1res.add("Steve Ballmer");
button1.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button1.getText());
button2.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button2.getText());
button3.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button3.getText());
button4.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button4.getText());
}
}
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
case R.id.button2:
case R.id.button3:
case R.id.button4:
}
}
}
What id does is this:
Choose 1 question from that arraylist of questions. Create the buttons, and put the chosen question in a string, and show that string on the screen. If that string is 'Who is the actual CEO at Apple?' then randomly put Steve Jobs and all those answers on buttons.
What I want is this:
If the user presses the button that contains: 'Tim Cook' then:
Remove 'Who is the actual CEO at Apple?' from the questions list, and randomly chose another question from the ArrayList of questions, and randomly put the answers on the buttons (the same stuff I already did, just that is another question).
My problem is that I can't really have acces to the array to delete it,because all I got is the case when the button is pressed.I tried to make a function,but every time I execute the function,the list is always recreated....
Can someone correct the code for me? And add what is missing?
Put the code that displays a random question in a new method (let's call it displayNewQuestion()) and let questions1 be a field of your Activity class. displayNewQuestion will then be able to use the activity-wide question array, and the click handler can remove a question out of it.
Try to change the scope of the ArrayList (use a private member for example) to enable access from your onClick method… I assume you'll have to do the same with your adapter to tweak it to your needs.
Update:
A quick-and-dirty implementation (without adapter nor ViewHolder, etc.):
package com.stackoverflow.randomarray;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SoRandomArray extends Activity implements View.OnClickListener {
private Random mRandom = new Random();
private List<String> mQuestionsList;
private String mCurrentQuestion = null;
private List<String> mAnswersList;
TextView mQuestionTv;
Button mButton1;
Button mButton2;
Button mButton3;
Button mButton4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mQuestionsList = new ArrayList<String>();
mAnswersList = new ArrayList<String>();
initQuizData();
mQuestionTv = (TextView)findViewById(R.id.textView1);
// Retrieve the buttons declared by the xml layout
mButton1 = (Button)findViewById(R.id.button1);
mButton2 = (Button)findViewById(R.id.button2);
mButton3 = (Button)findViewById(R.id.button3);
mButton4 = (Button)findViewById(R.id.button4);
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
mButton3.setOnClickListener(this);
mButton4.setOnClickListener(this);
shuffle();
}
private void initQuizData() {
mQuestionsList.add("Who is the actual CEO at Apple?");
mQuestionsList.add("Who is the actual CEO at Microsoft?");
mQuestionsList.add("Android is made by:");
mAnswersList.add("Steve Jobs");
mAnswersList.add("Steven Sinofsky");
mAnswersList.add("Tim Cook");
mAnswersList.add("Steve Ballmer");
}
private void shuffle() {
mCurrentQuestion = mQuestionsList.get(mRandom.nextInt(mQuestionsList.size()));
mQuestionsList.remove(mCurrentQuestion);
mQuestionTv.setText(mCurrentQuestion);
mAnswersList.add("Steve Jobs");
mAnswersList.add("Steven Sinofsky");
mAnswersList.add("Tim Cook");
mAnswersList.add("Steve Ballmer");
mButton1.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton1.getText());
mButton2.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton2.getText());
mButton3.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton3.getText());
mButton4.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton4.getText());
}
private boolean validateAnswer(String question, String answer) {
if(question.equals("Who is the actual CEO at Apple?")) {
if(answer.equals("Tim Cook")) {
return true;
} else {
return false;
}
} else if (question.equals("Android is made by:")) {
return false;
} else if (question.equals("Who is the actual CEO at Microsoft?")) {
if(answer.equals("Steve Ballmer")) {
return true;
} else {
return false;
}
}
return false;
}
public void onClick(View v) {
Toast toast;
if(validateAnswer(mCurrentQuestion, ((Button)findViewById(v.getId())).getText().toString())) {
toast = Toast.makeText(this, "Good!", Toast.LENGTH_SHORT);
} else {
toast = Toast.makeText(this, "Too bad!", Toast.LENGTH_SHORT);
}
if(mQuestionsList.size()>0) {
toast.show();
shuffle();
} else {
toast.show();
}
}
}
The associated layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, SoRandomArray"
/>
<Button
android:id="#+id/button1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=""
/>
<Button
android:id="#+id/button2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=""
/>
<Button
android:id="#+id/button3"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=""
/>
<Button
android:id="#+id/button4"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="" />
</LinearLayout>
You'll have to correct some issue with the randomizing of the buttons, that's not state-of-the-art but that's the idea and it will give you a start…