How do you make buttons - Java for Android App Development

Hello,
I am now making an App for a hospital. I am making the App with Androidstudio but I cant make a button. I have got 4 buttons, but if I click on them they will do nothing. How can I program that if I clicked on them that they will do something? Please help me I can't figure out how could I do this.
Thanks in Advance

Go through the training session on developer.android.com
Sent from my GT-S5570 using XDA Premium 4 mobile app

what i do is use androidnClick="TAG_HIER"
and the make a simple .ethod ( will write / post hier when i am home )
which launches ( apps or sites etc.)
mostly when u type
Button onclick method
on google you will find some gokd tuts
stackoverflow good help aswell
Sent from my S500 using xda app-developers app

poyu said:
Hello,
I am now making an App for a hospital. I am making the App with Androidstudio but I cant make a button. I have got 4 buttons, but if I click on them they will do nothing. How can I program that if I clicked on them that they will do something? Please help me I can't figure out how could I do this.
Thanks in Advance
Click to expand...
Click to collapse
First go to you activity.java file and initialize a button
Code:
private static Button button1;
Then link it with the button in xml using it's id
Code:
button1= (Button) rootView.findViewById(R.id.button1);
Then add a listener where you define what happens on button press.
Code:
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
system.out.println("Button pressed");
}
});

gh0stslayer said:
First go to you activity.java file and initialize a button
Code:
private static Button button1;
Then link it with the button in xml using it's id
Code:
button1= (Button) rootView.findViewById(R.id.button1);
Then add a listener where you define what happens on button press.
Code:
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
system.out.println("Button pressed");
}
});
[/QUOTE
Thank you very much, but when I did this it gave me a message that I pressed a button. What I want is that when i press the button that I will go to an other page. A new page. How can I get this done. I appreciate it a lot that you have done this for me
Click to expand...
Click to collapse

poyu said:
gh0stslayer said:
First go to you activity.java file and initialize a button
Code:
private static Button button1;
Then link it with the button in xml using it's id
Code:
button1= (Button) rootView.findViewById(R.id.button1);
Then add a listener where you define what happens on button press.
Code:
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
system.out.println("Button pressed");
}
});
[/QUOTE
Thank you very much, but when I did this it gave me a message that I pressed a button. What I want is that when i press the button that I will go to an other page. A new page. How can I get this done. I appreciate it a lot that you have done this for me
Click to expand...
Click to collapse
to go to another activity ,you have to use intents
inside on click put these lines
Code:
Intent intent = new Intent(this, anotheractivity.class);
startActivity(intent);
if you are using fragments, use getActivity() instead of this.
Sent from my Galaxy Nexus using Tapatalk
Click to expand...
Click to collapse

How do you make a button that is only enabled if there is text in the textfields in a fragmentactivityQUOTE=gh0stslayer;52131883]
poyu said:
to go to another activity ,you have to use intents
inside on click put these lines
Code:
Intent intent = new Intent(this, anotheractivity.class);
startActivity(intent);
if you are using fragments, use getActivity() instead of this.
Sent from my Galaxy Nexus using Tapatalk
Click to expand...
Click to collapse

How do you make a button that is only enabled if there is text in the textfields in a fragmentactivityQUOTE=gh0stslayer;52131883]
poyu said:
to go to another activity ,you have to use intents
inside on click put these lines
Code:
Intent intent = new Intent(this, anotheractivity.class);
startActivity(intent);
if you are using fragments, use getActivity() instead of this.
Sent from my Galaxy Nexus using Tapatalk
Click to expand...
Click to collapse

poyu said:
How do you make a button that is only enabled if there is text in the textfields in a fragmentactivityQUOTE=gh0stslayer;52131883]
Click to expand...
Click to collapse
you will have to use onEdittext change listener, here is an example
http://stackoverflow.com/questions/4310525/android-on-edittext-changed-listener

Related

Button2 doesnt work until Button1 is clicked

Hi All!
I'm new here and new to the Android Eclipse/development side and I'm having a bit of a problem with a java script.
I have a small advertising app with 2 buttons (looking to expand to 4 but that's a different thread), one for Facebook (Button1) and one for Twitter (Button2) and Button2 won't work until Button1 is clicked. It works fine except for that.
Any ideas on solutions? Aggravating me a bit lol
Thanks!!
We will need to see your layout XML and java code to help out.
not sure how i'd do that atm cos im a new member? i know that some admin members get pi**y when you dont wrap any code for formatting reasons??
i've got ready and i can imagine a senior member such as yourself will notice the mistake straight away.
Use pastebin http://pastebin.com/
not sure how to use it, just tried and i got the same message about not being able to post things outside links until 10 posts and so on? even tried pasting the raw text and still wouldnt let me
any suggestions?
thanks
Or use the CODE tags: [CODE ] and [/CODE ], but without the extra spaces.
adamj1910 said:
not sure how to use it, just tried and i got the same message about not being able to post things outside links until 10 posts and so on? even tried pasting the raw text and still wouldnt let me
any suggestions?
thanks
Click to expand...
Click to collapse
Take http off or www and just paste it as text
pastebin.com/4Q0g9ryg
pastebin.com/rHvFePNM
hopefully that should work?
thanks!
You had your button definition in the wrong place for your twitter button
Code:
package com.MYAPP.MYAPP;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Set the screen's view to your xml file
Button facebookbutton = (Button) findViewById(R.id.button1); // Retrieve the button from the XML file
facebookbutton.setOnClickListener(new View.OnClickListener() { //Add a listener for when the button is pressed
[user=439709]@override[/user]
public void onClick(View v) {
sendToFacebook();
}
});
Button twitterbutton = (Button) findViewById(R.id.button2); // Retrieve the button from the XML file
twitterbutton.setOnClickListener(new View.OnClickListener() { //Add a listener for when the button is pressed
[user=439709]@override[/user]
public void onClick(View v) {
sendToTwitter();
}
});
}
protected void sendToFacebook() {
String url = "https://www.facebook.com"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
i.setData(Uri.parse(url)); // Add the url data (allowing android to realise you want to open the browser)
startActivity(i); // Go go go!
}
protected void sendToTwitter() {
String url = "https://www.twitter.com"; // You could have this at the top of the class as a constant, or pass it in as a method variable, if you wish to send to multiple websites
Intent i = new Intent(Intent.ACTION_VIEW); // Create a new intent - stating you want to 'view something'
i.setData(Uri.parse(url)); // Add the url data (allowing android to realise you want to open the browser)
startActivity(i); // Go go go!
}
}
Thanks for that ill give that a try!!! Really appreciate it
Sent from my GT-I9305 using xda app-developers app
it works!!! would i just repeat that for any additional buttons, same format;
Button onclicklistener etc etc etc
Button onclicklistener etc etc etc
protected void
protected void
and so on
does it work like that?
thanks!
Yes, just besure you place the code in your onCreate method for defining your buttons
Ill remember that haha thanks again really appreciate it!! =D
Sent from my GT-I9305 using xda app-developers app
zalez said:
Yes, just besure you place the code in your onCreate method for defining your buttons
Click to expand...
Click to collapse
Hey zalez
I just tried adding a youtube button in the exact same format obviously changing the button source and so on, eclipse couldn't find any problems so I ran it and it just crashed the app on the avd and on a real device?
Sent from my GT-I9305 using xda app-developers app
There are multiple ways. I like setting a listener, then using an onClick method with switch-case statements for every button.
Sent from my GT-I9300 using Tapatalk 4
you've lost me lol i understand the onclick but switch cases? if you check my .xml and .java from pastebin or the .java that another member posted further up ^ ^ ^ ^ that might show where im going wrong?
edit *** i just googled the switch case thing and ive seen it before, just not sure how i'd implement it into my .java?
thanks
bump?
adamj1910 said:
you've lost me lol i understand the onclick but switch cases? if you check my .xml and .java from pastebin or the .java that another member posted further up ^ ^ ^ ^ that might show where im going wrong?
edit *** i just googled the switch case thing and ive seen it before, just not sure how i'd implement it into my .java?
thanks
Click to expand...
Click to collapse
Sorry, I'm away. I'll look up an example from one of my apps later.
Basically, just make an onClickListener. You are then required to use that interface and implement the onClick method. Do that, you have an empty method, with a parameter like View v.
Then, make a switch statement for v.getId(), and do cases for the buttons (use their XML IDs!) that you have.
Hope that's kind of clear?
Sent from my GT-I9300 using Tapatalk 4
bassie1995 said:
Sorry, I'm away. I'll look up an example from one of my apps later.
Basically, just make an onClickListener. You are then required to use that interface and implement the onClick method. Do that, you have an empty method, with a parameter like View v.
Then, make a switch statement for v.getId(), and do cases for the buttons (use their XML IDs!) that you have.
Hope that's kind of clear?
Sent from my GT-I9300 using Tapatalk 4
Click to expand...
Click to collapse
That's actually starting to make sense! But it's just putting that into a script, not really my strong point yet, I'm more of a designer lol
It would be good if you could find some examples for URL buttons, it'd really help. Thanks!
There shouldn't have been any issues adding more. I would need to see your updated java code. Using switch cases is a good idea but at this point, if I was you, I would avoid it for now until you get the hang of the basics. Also, a log cat would be beneficial in debugging.

[NoobGuide]Click back button twice to Exit from Application

HI Guys
This is my first post in android app developement forum.
A small snippet of code which I use to exit from android app .
Many times we have more than one activites in app and often these activities are inter linked.
suppose we have four activities A-> B- ->C->D with A as root activity
Now consider user move from A to B then B--> C then come to A and moves to D
Now when user press back he returns to A
At this some app requires to be close and it should not navigate in history of activity stack ie
going to B then C then again A and finaly exit.
So the solution here is to close the app when user is in A acitivity since its Root activity.
Below is the code for that:
Code:
private static long back_pressed;
private Toast toast;
[user=439709]@override[/user]
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis())
{
// need to cancel the toast here
toast.cancel();
// code for exit
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
// ask user to press back button one more time to close app
toast= Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT);
toast.show();
}
back_pressed = System.currentTimeMillis();
}
Add this code in your root activity so that it wont let app go into history stack.
Also you may write dialog instead of toast message
:good:
Nice snippet, thanks!
Sent from my GT-N7000 using Tapatalk 4

[Q] Button Listener

I'm writing a simple app that changes the background color of my RelativeLayout depending on what button I press (i.e btnRed changes the color to Red).
I was wondering, instead of writing multiple onClickListener methods for each button, is there a way I can just listen for an OnClick action, and depending on what button was click, change the background to the respective color?
Much appreciated!
Take a look here: http://stackoverflow.com/questions/3795439/one-onclickhandler-for-multiple-buttons
you can create onclick method
and then use switch for all buttons.
Ex.
public void onClick(View v){
switch view.getId()
{
case R.id.button1:
break;
case R.id.button2:
break;
}
}
Click to expand...
Click to collapse
you can create for all buttons.
wasim memon said:
you can create onclick method
and then use switch for all buttons.
you can create for all buttons.
Click to expand...
Click to collapse
But you also have to call this:
Code:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
Additionally, your app has to implement View.OnClickListener.
And alternative would be adding the method in the xml file like this:
Code:
<Button
...
android:onClick="onClick" />
But this thread is 2 weeks old and there is a working solution. Please don't bring old threads to the front again.

[Q]How to expand status bar from app

I want to know the the code which is used to expand status bar using EXPAND_STATUS_BAR permission (by maybe intent).
Sent from my GT-S5570 using XDA Premium 4 mobile app
Have a look at this: http://stackoverflow.com/questions/7021310/how-to-open-or-expand-status-bar-through-intent
(Also read the comments for the 4.2 solution.)
You can also find a Github Gist on that topic here: https://gist.github.com/tom-dignan/2468681 (Support for 4.2+ is missing in that.)
nikwen said:
Have a look at this: http://stackoverflow.com/questions/7021310/how-to-open-or-expand-status-bar-through-intent
(Also read the comments for the 4.2 solution.)
You can also find a Github Gist on that topic here: https://gist.github.com/tom-dignan/2468681 (Support for 4.2+ is missing in that.)
Click to expand...
Click to collapse
I have already tried this but aide says unknown entity 'method'.i dont know what i have to import to solve this.
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
I have already tried this but aide says unknown entity 'method'.i dont know what i have to import to solve this.
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Do a long press on the underlined word. Select Fix > Import. That should import the right class.
Thanks it worked
Sent from my GT-S5570 using XDA Premium 4 mobile app
But there is one problem.
I also added a start Activity intent along with this code but surprisingly activity doesnt started rather app also exited(not fc)
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
But there is one problem.
I also added a start Activity intent along with this code but surprisingly activity doesnt started rather app also exited(not fc)
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Code?
Code:
public void login(View view){
EditText username=(EditText) findViewById(R.id.username);
EditText password=(EditText) findViewById(R.id.password);
try{
File x=new File("/data/data/com.rockstudios.savedata/login.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(x);
doc.getDocumentElement().normalize();
String u = doc.getElementsByTagName("username").item(0).getTextContent();
String d=doc.getElementsByTagName("password").item(0).getTextContent();
if(username.getText().toString().equals(u) && password.getText().toString().equals(d)){
Object service=getSystemService("statusbar");
Class<?> statusbarManager =Class.forName("android.app.StatusBarManager");
Method expand=statusbarManager.getMethod("expand");
expand.invoke(service);
startActivity(new Intent(this,MainActivity.class));
}else{
Toast.makeText(this,"Wrong Username/password",5000).show();
}
} catch (Exception e) {Toast.makeText(this,"error"+e,5000).show();
}}
Actually app hangs when details are correct and expanded statusbar is collapsed by user .touching anywhere makes it exit
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
Code:
public void login(View view){
EditText username=(EditText) findViewById(R.id.username);
EditText password=(EditText) findViewById(R.id.password);
try{
File x=new File("/data/data/com.rockstudios.savedata/login.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(x);
doc.getDocumentElement().normalize();
String u = doc.getElementsByTagName("username").item(0).getTextContent();
String d=doc.getElementsByTagName("password").item(0).getTextContent();
if(username.getText().toString().equals(u) && password.getText().toString().equals(d)){
Object service=getSystemService("statusbar");
Class statusbarManager =Class.forName("android.app.StatusBarManager");
Method expand=statusbarManager.getMethod("expand");
expand.invoke(service);
startActivity(new Intent(this,MainActivity.class));
}else{
Toast.makeText(this,"Wrong Username/password",5000).show();
}
} catch (Exception e) {Toast.makeText(this,"error"+e,5000).show();
}}
Actually app hangs when details are correct and expanded statusbar is collapsed by user .touching anywhere makes it exit
Click to expand...
Click to collapse
Thats probably because the onPause() method is called on expanding the statusbar. If you want to start the MainActivity when the user collapses the statusbar, add some Kind of boolean instance variable (e.g. startActivityFlag) that is set to true before you call expand.invoke(service) . Then override the onResume() method like this:
Code:
@Override
public void onResume() {
super.onResume();
if (startActivityFlag) startActivity(new Intent(this,MainActivity.class));
}
SimplicityApks said:
Thats probably because the onPause() method is called on expanding the statusbar. If you want to start the MainActivity when the user collapses the statusbar, add some Kind of boolean instance variable (e.g. startActivityFlag) that is set to true before you call expand.invoke(service) . Then override the onResume() method like this:
Code:
@Override
public void onResume() {
super.onResume();
if (startActivityFlag) startActivity(new Intent(this,MainActivity.class));
}
Click to expand...
Click to collapse
I will try this.does expanding of status bar pauses the background app?
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
I will try this.does expanding of status bar pauses the background app?
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
I haven't actually tested it, but it should: http://developer.android.com/training/basics/activity-lifecycle/pausing.html

[Q] Need Help with a problem

I am using one edit text view and one OK button to input a large amount of user data during a setup function but can't figure out how to pause the thread execution unit the OK button is pressed. I don't want to have to register and use a ton of different buttons and listeners to call individual functions for each user input and so far I've found out the hard way that a while look will lock the UI thread and running the loop in a separate thread will not make the program wait. Any Ideas?
public class SetupMenuActivity extends Activity
{
private TextView setupPrompt;
boolean okButtonPressed = false;
@override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_menu);
setup();
}
private OnClickListener okButtonListener = new OnClickListener()
{
@override
public void onClick(View v)
{
okButtonPressed = true;
}
};
private void setup()
{
Button okButton = (Button) findViewById(R.id.okButton);
okButton.setOnClickListener(okButtonListener);
setupPrompt = (TextView) findViewById(R.id.setupPrompt);
setupPrompt.setText("Please Enter Your Name");
// Make program wait for ok button clicked
setupPrompt.setText("Please Enter a Name for your Account");
}
}
What else could the user click/etc that you want to prevent from happening? If you want to block another button, then you can either do button.setClickable(false) or even button.setVisibility(View.GONE) until the ok button is clicked. Instead blocking the whole thread doesn't make much sense
The only two things the user can interact with is the button and the edit text box. I want to prevent the changing of the setupPrompt text view until the Ok button is pressed. The easy way to do it would be to put it into the onClickListener but there is a whole series of the prompts and waiting for user input so I'm trying to avoid creating a ton of different button listeners for each piece of user input.
TShipman1981 said:
The only two things the user can interact with is the button and the edit text box. I want to prevent the changing of the setupPrompt text view until the Ok button is pressed. The easy way to do it would be to put it into the onClickListener but there is a whole series of the prompts and waiting for user input so I'm trying to avoid creating a ton of different button listeners for each piece of user input.
Click to expand...
Click to collapse
The way you think this would work is not right, you have to think through it again, sorry . In Android, you can almost never wait for user events (because they might not happen). Instead, you have to do what you can during setup and everything that can only happen after a certain event has to be in the onEvent method (for instance onClick). What you can do to make it less complex is one method which is called only from the onClickListener. The method keeps track of how many times it has been called with an int step instance variable. That method has to execute what should happen at each step.
SimplicityApks said:
The way you think this would work is not right, you have to think through it again, sorry . In Android, you can almost never wait for user events (because they might not happen). Instead, you have to do what you can during setup and everything that can only happen after a certain event has to be in the onEvent method (for instance onClick). What you can do to make it less complex is one method which is called only from the onClickListener. The method keeps track of how many times it has been called with an int step instance variable. That method has to execute what should happen at each step.
Click to expand...
Click to collapse
Yeah Agreed with Simp. I would honestly make one method with all the info you need then get all the info and call it only when the button is clicked. If I knew a bit more of what your trying to accomplish I might be able to help you code it more efficiently.

Categories

Resources