Im very new at this and I really searched for the answer.
I know this question will be very easy, but I really need help.
I have multiple ImageButtons, but dont know how I make different OnClicklistener for them.
This is my code, and I think something is missing here.
ImageButton facebookButton = (ImageButton) findViewById(R.id.imageButtonFacebook);
ImageButton twitterButton = (ImageButton) findViewById(R.id.imageButtonTwitter);
facebookButton.setOnClickListener(new View.OnClickListener() {
twitterButton.setOnClickListener(new View.OnClickListener() {
}
})
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButtonFacebook:
Intent fb = new Intent (MainActivity.this, FacebookActivity.class);
startActivity(fb);
break;
case R.id.imageButtonTwitter:
Intent tw = new Intent (MainActivity.this, TwitterActivity.class);
startActivity(tw);
break;
What is the problem?
Implement View.OnClickListener:
public class MyClass extends Activity implements OnClickListener {...}
and then set the OnClickListeners like this:
facebookButton.setOnClickListener(this);
twitterButton.setOnClickListener(this);
Related
Always in my apps I added buttons in void onCreate, but now I'm trying to do app with more buttons (about 10). I would like to all buttons active on start app.
In my opinion it is too much buttons to add in this onCreate and app will be starting to long.
I tried to put this:
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
})
out of onCreate
but AndroidStudio underlines setOnClickListener and view
I don't have ideas, how and where can i add button out of onCreate.
If you don't want to overcrowd your oncreate method, then create a clicklistener outside onCreate anywhere in activity and in onCreate just set it.
onCreate :
edit_a_member = (Button) findViewById(R.id.edit_member);
delete_a_member = (Button) findViewById(R.id.delete_member);
edit_a_member.setOnClickListener(handleClick);
delete_a_member.setOnClickListener(handleClick);
clickListener:
private View.OnClickListener handleClick = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.edit_member:
member_selected = EDIT_MEMBER_SELECTED;
callDialog();
break;
case R.id.delete_member:
callDeleteAlert();
break;
}
}
};
You can simply add a separate method for your buttons in the same class, e.g.:
public void onCreate(...){
//Standard setup of views or whatever you want to do here
this.addButtons();
}
private void addButtons(){
Button b1 = new Button("Hi");
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
Button b2 = new Button("Hi to you too");
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
}
This is an example. You can do this in soooo many ways. I feel like you should thoroughly learn Java's fundamental Object Oriented programming, because that's really what your question suggests you don't understand. Go follow a youtube tutorial. I always like "The New Boston"'s Java tutorial series on youtube.
PS: You can make code like this beautiful under the 'Words of wisdom': Don't repeat yourself
If you have to do a lot of work in your onCreate but you are worried that the UI will take too long to load you can always post a delayed runnable to a handler so in the onCreate method put :
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//add your code here
}
},10);
what this will do is your UI will load then the code in your Runnable will be executed 10 milliseconds after your UI loads thus your app will not take too long to load the UI, even though in your case I doubt it would be necessary.
If you are declaring the buttons in xml file :
Add these properties in each button Declaration in your Xml :
android:clickable="true"
android:onClick="onClick"
And now in Activity Class create a method like this :
public void onClick(View v){
switch(v.getId){
case R.id.{buttons_id_in_xml}
(Your Code)
break;
(Like for others)
}
}
If you want to add buttons dynamically :
Create a method to add the button like this:
void addButton(String buttonName, int button id){
Button button = new Button(this);
button.setText("Push Me");
(add it to parent Layout of xml)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(id){
case id1:
(handle )
break;
(like for others)
}
}
});
}
The best way to do this is:
add implements View.OnClickListener to
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// declare variables
private Button mBtn1;
private Button mBtn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// make an instance to the btns
mBtn1 = findViewById(R.id.btn1);
mBtn2 = findViewById(R.id.btn2);
// set onClickListener
mBtn1.setOnClickListener(this); // with "this" you are passing the view
mBtn2.setOnClickListener(this);
}
// implement onClick
#Override
public void onClick(View view) {
// check which btn was clicked by id
switch (view.getId()) {
case R.id.btn1:
btn1Clicked();
break;
case R.id.btn2:
btn2Clicked();
break;
}
}
private void btn1Clicked() {
// your code btn1 clicked
}
private void btn2Clicked() {
// your code btn2 clicked
}
Hope this helped. Cheers!
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 7 years ago.
I was trying to pass a variable named choice to another class but I do not know how I should go along doing this because it is inside the onClick. Here is an example of what I am trying to do.
public int choice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//intent for first button
Button button1= (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
choice = 1;
startActivity(new Intent(MainActivity.this,Celeb1.class));
}
});
//intent for second button
Button button2= (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
choice = 2;
startActivity(new Intent(MainActivity.this,Celeb1.class));
}
});
}
In a different class I would like to check if choice is equal to 1 or 0 and execute some code.
You can pass variable by this way
Intent intent = new Intent(MainActivity.this,Celeb1.class)
intent.putExtra("choice", 1);
startActivity(intent);
And in Celeb1 class you can get variable by using
Bundle extras = getIntent().getExtras();
int choice= extras.getInt("choice");
inside onCreate()
//in main activity
Intent i=new Intent(getApplicationContext(),Celeb1.class);
i.putExtra("name","stack");//name is key stack is value
startActivity(i);
//In Celeb1 class
Intent i=getIntent();
String name=i.getStringExtra("name");
Do not make instance of Intent instead make object of Intent and pass extra values to your class
choice = 2;
Intent intent = new Intent(MainActivity.this, Celeb1.class);
intent.putExtra("choice",choice);
startActivity(intent);
That's It
I am android beginner, Hope It will help you.
I want to make buttons once I click on the button I go to another activity?
and the problem is only the first button is working!
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button PageOneButton = (Button) findViewById(R.id.btnPageOne);
PageOneButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), PageOne.class);
v.getContext().startActivity(myIntent);
Button PageTwo = (Button) findViewById(R.id.btnPageTwo);
PageTwoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), PageTwo.class);
v.getContext().startActivity(myIntent);
}
{}
});
}
});
}
}
Think it is because most of your code is closed inside the scope of the first onClickListener, try something like this.
Button PageOneButton = (Button) findViewById(R.id.btnPageOne);
PageOneButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent myIntent = new Intent(Main.this, PageOne.class);
startActivity(myIntent);
});
Button PageTwoButton = (Button) findViewById(R.id.btnPageTwo);
PageTwoButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent myIntent = new Intent(Main.this, PageTwo.class);
startActivity(myIntent);
});
Using v.getContext() should be ok, this is just how I usually would do as the Activity itself is indeed a valid context. I guess it just seems more readable to me.
Edit:
Just as a clarification to the current state of your code. The second button is assigned a onClickListener only after the first button is pressed. But since the first button takes the app to a new Activity, inherently destroying the Main Activity, the second button will never have a chance to reach it's onClickListener.
Hope it makes sense, nevertheless the code above should fix the issue.
There are a couple of issues currently in your code. The first issue is that your second button is being defined inside the first button's declaration. The next issue is that you're setting the second OnClickListener to the wrongly named button. You've made a typo and instead of PageTwo, which you've called the Button (presumably you wanted to call it PageTwoButton in accordance with the first Button) and then set the OnClickListener to PageTwoButton instead. Seeing as you're also using multiple Buttons, it's a lot cleaner and more efficient to use a GroupOnClickListener. I'd probably also suggest using 'this' instead of 'v.getContext()' as well when setting up your Intents. Change your code to be like so:
Button PageOneButton = (Button) findViewById(R.id.btnPageOne);
Button PageTwoButton = (Button) findViewById(R.id.btnPageTwo);
PageOneButton.setOnClickListener(addGroupOnClickListener);
PageTwoButton.setOnClickListener(addGroupOnClickListener);
private OnClickListener addGroupOnClickListener = new OnClickListener() {
public void onClick(View v) {
if (v == PageOneButton) {
Intent myIntent = new Intent(Main.this, PageOne.class);
startActivity(myIntent);
} else if (v == PageTwoButton) {
Intent myIntent = new Intent(Main.this, PageTwo.class);
startActivity(myIntent);
}
}
};
Hope this helps!
Two words: Code Indentation
Were you to indent your code properly, you would have noticed that you're setting OnClickListener INSIDE your first buttons' listener. Move it outside your first listener, as has already been advised by others.
There's also an extra pair of {}, which is redundant.
Also, #edwoollard noticed that for the second button, you're using two different names, PageTwo and PageTwoButton. Keep that in mind, unless it's a typo.
I am making a log-in system on Android. And I want the register Button to be unclickable when it has been clicked. I am using this code:
final Button register = (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register.setEnabled(false);
Intent register = new Intent(getApplicationContext(), register.class);
startActivity(register);
}
});
This is working great, but I want the Button to remain unclickable even when the application or phone has been restarted. Does anyone know a way to make the Button unclickable permanently even when the application has been shut down?
As I already said in the comments section something like this may work:
public class MyActivity extends Activity {
private static final String KEY_IS_BUTTON_CLICKABLE = "key_clickable";
#Override
public void onCreate(Bundle savedInstanceState) {
...
final Button register = (Button) findViewById(R.id.register);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean isClickable = sharedPreferences.getBoolean(KEY_IS_BUTTON_CLICKABLE, true);
register.setEnabled(isClickable);
if(isClickable) {
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register.setEnabled(false);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
.putBoolean(KEY_IS_BUTTON_CLICKABLE, false);
Intent register = new Intent(getApplicationContext(), register.class);
startActivity(register);
}
});
}
}
...
}
In this case you could take a pessimistic approach and disable the button in the layout (by default) with android:clickable="false" and enable it in the condition where registration is required.
How to navigate from one Activity screen to another Activity screen? In the first screen I'm having one button if I click the button it has to move to another Activity screen.
The most trivial case (called from activity):
startActivity(new Intent(this, ActivityToLaunch.class));
More details here: http://developer.android.com/guide/topics/fundamentals.html
OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(action));
}
};
Button button = (Button) findViewById(id);
button.setOnClickListener(onClickListener);
Button x.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent i = new Intent(y.this, Activity.class);
startActivity(i);
}
});
Here we've defined a listener for Button x. The OS will call this method and start the Activity referenced in Intent i.
Here's the official tutorial example:
http://developer.android.com/guide/tutorials/notepad/notepad-ex2.html
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(TestActivity.this,second.class));
}
});
public void onClick(View v)
{
Intent myintent = new Intent(currentclass.this, nextactivity.class);
startActivity(myintent);
}
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent) which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent) -- Used to launch a new activity.
So suppose you have two Activity class and on a button click's OnClickListener() you wanna move from one Activity to another then --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
This exmple is related to button click you can use the code anywhere which is written inside button click's OnClickListener() at any place where you want to switch between your activities.
final Context cont = this;
Button btnClickABC =(Button)findViewById(R.id.btnClickABC);
btnClickABC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(cont, NextActivity.class));
}
});
Use following code..I hope this will help you.
Button button = (Button)findViewById(R.id.xxx);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
startActivity(intent);
}
});
xxx is id from your xml of your Button.
startActivity(new Intent(this,newActivity.class));
Switching from one activity to another is really simple, but tricky for a new one.
Your next class must be defined in AndroidManifest.xml. This is tester class:
<activity
android:name=".Tester"
android:label="#string/title_activity_tester" >`enter code here`
</activity>
final Button button = (Button) findViewById(R.id.btnGo);// btnGo is id
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(CurrentClass.this, Tester.class);
startActivity(i);
}
You can navigate to the next screen using these code snippets:
Kotlin
startActivity(Intent(this, LoginActivity::class.java))
Java
startActivity(new Intent(this, LoginActivity.class))
Here's a reference: Android Developers - Starting another activity
Intent intentobj=new Intent(FromActivity.this,ToActivity.class);
startActivity(intentobj);
or you can simply use
startActivity(new Intent(FromActivity.this,ToActivity.class));
For Kotlin (if you are in an activity)
buttonToClick.setOnClickListener{ startActivity(this,YourDestinationActivity::class.java)
}
If you are in a fragment
buttonToClick.setOnClickListener{
startActivity(requireActivity, YourDestinationActivity::class.java)
}
In your method fun onCreate(savedInstanceState: Bundle?) add this.
your_btn_id.setOnClickListener{
val intent = Intent(this, yourpagename::class.java)
startActivity(intent)
}
Until now if it doesn't work then, check if these two files are added or not,
import android.content.Intent
import kotlinx.android.synthetic.main.activity_otp.*
Try this code:
Button my_btn;
my_btn = findViewById(R.id.submit_btn);
my_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_2);
}
});
Button navigate;
navigate = findViewById(R.id.button);
navigate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Navigate another Activity",Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
Just go to XML file and add Onclick = "opennewactivity" in button xml.
Then go to java code and create class opennewactivity you can just make it my clciking alt+Enter in xml code's "opennewactivity". in that just write
Intent intent = new Intent(this, newacivity.class);
startActivity(intent);
and if you want user to not get back to first activity again then just write this
Intent intent = new Intent(this, newactivity.class);
startActivity(intent);
finish();
Cartoon_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
newActivity();
}
});
}
public void newActivity()
{
Intent selectClass= new Intent(getApplicationContext(), com.example.fyp.videoplayer.class);
startActivity(selectClass);
}