Android Studio imageButton and switching to another Activity - android

UPDATE:
I have 4 imageButtons and each one needs a "setOnClickListener" or similar. Once the listener fires, I have an intent to take the user to the next Activity, which is currently just a blank page:
public void onClick(View v){
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
I started out with 4 Buttons, and had it all working, and then decided to use imageButtons instead for aesthetics.
I'm not sure what the difference is in "buttons" and "imageButtons" are, but you most certainly can't interchange them. My best 'Googling' has not turned up any solution so far in understanding how to modify my earlier 'button' solution.
Any assist would be welcome,
Ed
Here is the MainActivity.java code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//In this next line, note that 'btn' will never be used, it's
//grayed out in the "Button btn...", and in the (R.id.btn) it is
//shown in red font, indicating I probably need to declare a resource of some kind?
Button btn = (Button)findViewById(R.id.btn);
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is the activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:clickable="true">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:background="#drawable/new_song"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton2"
android:background="#drawable/loadsong"
android:layout_alignTop="#+id/imageButton"
android:layout_toRightOf="#+id/imageButton"
android:layout_toEndOf="#+id/imageButton"
android:layout_marginLeft="55dp"
android:layout_marginStart="55dp"/>
</RelativeLayout>

ImageButton in Android is not a subclass of Button, but of ImageView, so you can't store a ImageButton in a Button variable. So you need to use ImageButton as your button object class. The method setOnClickListener is not static and should be set on the button object you want to use. Also the Button id you try to use is not in your xml (at least not the part you posted). So your code should read sth like this:
ImageButton btn = (ImageButton)findViewById(R.id.imageButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
});

If you originally had buttons that were working, you may have forgotten to change the cast type. For example
Button btn = (Button)findViewById(R.id.btn); //Will work.
ImageButton btn = (Button)findViewById(R.id.btn); //Might compile, but will not work.
Alternatively, if you left the XML tag as a normal button
<Button android:id = .../>
and tried to cast it to an image button, an error would be thrown. You would need to change the tag to <ImageButton android:id = .../>
Otherwise, I'm not sure what changes you made that would result in this going wrong. Further details as to the nature of the error would be helpful in solving the problem

You should ImageButton instead of Button.
Must use setOnClickListener to Button object btn instead of Button class
Update your onCreate() method as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton btn = (ImageButton) findViewById(R.id.imageButton);
ImageButton btn2 = (ImageButton) findViewById(R.id.imageButton2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NewSong.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do something...
}
});
}
Hope this will help~

Related

Android: Unable to call back buttonOnCklick [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Actually I don't understand why it doesn't see the buttonOnClick listener?
public class GeneralActivity extends AppCompatActivity {
// with or without these lines below
private View.OnClickListener buttonOnClick = this.buttonOnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalData.getInstance().gContext = this;
setContentView(R.layout.activity_general);
((TextView) findViewById(R.id.licence)).setText(MySettings.Values().LicenceNo);
Button connect = (Button)findViewById(R.id.connect);
connect.setOnClickListener(buttonOnClick);
Button send = (Button)findViewById(R.id.sendall);
send.setOnClickListener(buttonOnClick);
}
boolean clicked = false;
public static String LICENCE = "";
public void buttonOnClick(View v) {
MessageBox.Show("Connect me");
Button b = (Button) v;
if (b.getId() == R.id.connect) {
MessageBox.Show("Connect me");
return;
Also,
In GeneralActivitry designer everything is written out - onClick for both buttons and this method referred to the GeneralActivity.
Pls, see the movie and tell me what's wrong now?
youtube.com/watch?v=heD9QGKtusY&feature=youtu.be
FULL CODE OF GENERALACTIVITY LAYOUT:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="#+id/licence"
android:layout_width="match_parent"
android:layout_height="30pt"
android:ems="10"
android:hint="1SAT"
android:inputType="textPersonName"
android:layout_weight="0"
android:singleLine="true"
android:text="SATEST LICENCE NUMBER" />
<Button
android:id="#+id/connect"
android:layout_width="match_parent"
android:layout_height="30pt"
android:layout_weight="0"
android:onClick="buttonOnClick"
android:text="CONNECT" />
<LinearLayout
android:id="#+id/messages"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" />
<Button
android:id="#+id/sendall"
android:layout_width="match_parent"
android:layout_height="30pt"
android:layout_weight="0"
android:enabled="false"
android:onClick="buttonOnClick"
android:text="SEND2ALL" />
Well, I don't like this site exactly because of that kind of people who set -1 without any reason for that.. they just like shitters in that pages.
I explained my problem with MAXIMUM example and even VIDEO.. WHAT ELSE do you need to see to get the question clear? Idiots.
Ok, let they live, it is the shit policy of this site holders..
Now you read carefully what was my error:
When I implemented OnViewListener interface I forgot to mark the method onClick with #Override and another "BIG" mistake was that the handler name onClick I wrote from UPPER LETTER OnClick..
Actually that was my main mistake. Before publishing my Q here, I try to understand everything by myself, and I tried all of the suggestions that guys gave me.. but the
letter O and o
hmm you understood )))
I am 30 years in software developing, and these kind of mistakes are the hardest mistakes I have ever met. Same like brackets [ { jr (..
Thank you all for you help.. I'll set the Answer to the first one.. Thank you again.
you can use built it OnClick method to do this for you: here is an example of how to do it
just don't forget to implement View.OnClickListener in your Activity
`
public class GeneralActivity extends AppCompatActivity implements View.OnClickListener {
// with or without these lines below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalData.getInstance().gContext = this;
setContentView(R.layout.activity_general);
((TextView) findViewById(R.id.licence)).setText(MySettings.Values().LicenceNo);
Button connect = findViewById(R.id.connect);
connect.setOnClickListener(this);
Button send = findViewById(R.id.sendall);
send.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.connect:
//TODO
break;
case R.id.sendall:
//DO something
break;
}
}
`
Option - 1: You have already set the onClick listener to button from xml, so no need to set it again from java code. Remove those line.
public class GeneralActivity extends AppCompatActivity {
// with or without these lines below
//private View.OnClickListener buttonOnClick = this.buttonOnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
//Button connect = (Button) findViewById(R.id.connect);
//connect.setOnClickListener(buttonOnClick);
//Button send = (Button) findViewById(R.id.sendall);
//send.setOnClickListener(buttonOnClick);
}
public void buttonOnClick(View v) {
MessageBox.Show("Connect me");
if (v.getId() == R.id.connect) {
MessageBox.Show("Connect me");
return;
} else if(v.getId() == R.id.sendall) {
//Add your logic here
}
}
}
Option - 2: If you want to set the listener from java code, then remove onClick attribute from xml and set it like below from code:
public class GeneralActivity extends AppCompatActivity {
boolean clicked = false;
public static String LICENCE = "";
private View.OnClickListener buttonOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.connect:
// Your connect logic here
break;
case R.id.sendall:
// Your send all logic here
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalData.getInstance().gContext = this;
setContentView(R.layout.activity_general);
((TextView) findViewById(R.id.licence)).setText(MySettings.Values().LicenceNo);
Button connect = (Button) findViewById(R.id.connect);
Button send = (Button) findViewById(R.id.sendall);
connect.setOnClickListener(buttonOnClick);
send.setOnClickListener(buttonOnClick);
}
}
Solution:
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Button one = (Button) findViewById(R.id.oneButton);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.twoButton);
two.setOnClickListener(this);
}
//outside of your oncreate()
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
default:
break;
}
}
TIP: Enter new View. And then press Ctrl+Spacebar you will get the function auto generated.

what is better way to organize onclicklistener? [duplicate]

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();
}
}

Android ImageButton's image to be replaced with another image

I have an ImageButton and I want that onClick would replace it with another image (flip back and forth) and on a long press, would replace it to another image.
How can I do that?
I don't feel like reading long documentaries for this.
Set onClickListeners for your button then change the drawable. Since you don't have any code, the following is based on a dynamic ImageButton that only outlines how to perform the action you want. I suggest you define your ImageButton in your XML layout first and then use
iBtn = (ImageButton) findViewById(R.id.btnID);
ImageButton iBtn = new ImageButton(this);
iBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
iBtn.setImageDrawable(getResources().getDrawable(R.drawable.img1);
}
});
iBtn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
iBtn.setImageDrawable(getResources().getDrawable(R.drawable.img2);
return true;
}
});
If you're going to learn Android (or any language or platform really), you should really get comfortable reading the documentation provided, as it will give you answers to many basic questions, such as how to use various methods and classes.
That aside, you need to set both an OnClickListener and an OnLongClickListener for your button. Then inside those listeners, you'll need to set the image using the setImageResource() method. That method requires a drawable image, which you should have saved in your drawable folder (if not, put it there!)
You didn't post your existing code, so here's a generic example.
ImageButton button = (ImageButton) findViewById(R.id.img_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button.setImageResource(R.drawable.pic1);
}
});
button.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
button.setImageResource(R.drawable.pic2);
return true; // <-- This must be true.
}
});
You could read further about how to use any buttons in the button guide, you'll just be swapping for ImageButton where appropriate.
Add ImageButton to your layout :
<ImageButton
android:id="#+id/img_btn1"
android:src="#drawable/imgc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
and then add this code to your Activity Oncreate() method
ImageButton imageButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.img_btn1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageButton.setImageResource(R.drawable.imga);
}
});
imageButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
imageButton.setImageResource(R.drawable.imgb);
return true;
}
});
}
change imga , imgb, imgc names according to your images taht are placed in drawable folder

How to obtain and pass the value of a button

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();
}

I want to start another activity when it is clicked?

Well I have an activity which contains nothing but a relative layout with brown background,
and I want to start another activity if the users clicks anywhere on the screen, how would i do that ??
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
}
First, give ID to your RelativeLayout by putting android:id="#+id/relativeLayout" in your layout file then.
RelativeLayout l = (RelativeLayout) findViewById(R.id.relativeLayout1);
l.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// startActivity here
}
});
or without using your RelativeLayout just implement the onTouchEvent(MotionEvent) of activity
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_UP)
{
// start activity
}
return super.onTouchEvent(event);
}
Note: Not yet tried this code.
Add onClick attribute to your layout xml, and implement onClick method in your activity to start a new activity.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="onClick"
android:orientation="vertical" >
In your activity add an onClick method.
public void OnClick(View v) {
startActivity(new Intent(this,MyNewActivity.class));
}
I think your Mainscreen has Parent layout either Linear,Relative,Frame. Take reference of that and handle click listener.
Ex:
If your Parent layout is Linear.
LinearLayout linear=(LinearLayout)findViewById(R.id.linear);
linear.setOnClickListener(this);

Categories

Resources