[Q] Button Listener - Java for Android App Development

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.

Related

My newbie thread.

Some background: 10 years ago I had classes in basic, pascal, and c++( I missed something simple some where with functions or classes which messed me up in this I believe.)
So far I've watched a tutorial and set up my emulator and eclipse..
http://www.youtube.com/watch?v=z7bvrikkG7c
I then did a tutorial that ran my first program helloworld
http://www.youtube.com/watch?v=2gdhvwYUNJQ
I then did a tutorial and made a simple program that changes between two screens on a button click ( Why it is an hour long is beyond my understanding)
http://www.youtube.com/watch?v=m-C-QPGR2pM
I've proceeded to learning how to create menus and simply retrieved example code from the Google android site
Source: http://developer.android.com/guide/topics/ui/menus.html
Here's an example of this procedure, inside an Activity, wherein we create an Options Menu and handle item selections:
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
case MENU_QUIT:
quit();
return true;
}
return false;
}
Click to expand...
Click to collapse
As I copy and pasted it into ecplise within an Activity, I realize there is some assumed information that I am missing when i received a bunch of errors
So.. I found A video tutorial
http://www.youtube.com/watch?v=6UYNnQOxCS8
and it instructs me to make sure I put these two lines of codes in first
Private static final int MENU1 = MENU.FIRST;
private static final int MENU2 = MENU.FIRST + 1;
I under line the menu's because it gives me errors on them as well... there seems to be some assumed knowledge I'm missing as well....
What specific piece of information am I missing to not have known that i would need those two lines as well as what I need to do to know the appropriate fix out of the suggestions they give me...
Are there any online tutorials or videos that'll bring me up to speed specifically with programming android apps... all the stuff I find just keeps leading me down a path to where I realize I've gotten ahead of myself because people are teaching things while assuming certain knowledge is known.
The tutorial I am following and getting errors on is for an 8th grade class of students...
Me: I'm pissed at that java toturial...
http://forum.xda-developers.com/showpost.php?p=6521891&postcount=6
Bastards.
Following the suggestion from this post
http://forum.xda-developers.com/showpost.php?p=6522089&postcount=7
I obtained a copy of Hello android.
Following the example to create a menu I used the code
I place this into my strings.xml
<string name="settings_label">Settings...</string>
name="settings_title">Sudoku settings</string>
<string
<string name="settings_shortcut">s</string>
<string name="music_title">Music</string>
<string name="music_summary">Play background music</string>
<string name="hints_title">Hints</string>
<string name="hints_summary">Show hints during play</string>
Click to expand...
Click to collapse
I place this into my main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/settings"
android:title="@string/settings_label"
android:alphabeticShortcut="@string/settings_shortcut" />
</menu>
Click to expand...
Click to collapse
I import this files into my src app.java
right uner the other imports
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
Click to expand...
Click to collapse
I place this inside my activity ( where I think it would belong since it doesn't say where to put it. ) and ERROR
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
Click to expand...
Click to collapse
Quick fix says that menu needs to be either a field or constast so i give it a go and click field and it modifies a file called R.java.
I go back to app.java and not only is the menu highlighted but now R.menu.menu is entirely highlighted and says cannot be resolved or is not a field..
I try to modify the R.java file to remove what its done...
It won't let me..
Epic fail. on the third tutorial to create a menu.
I guess ill redo everything in a new project and then do the quick fix making menu a constant....
[edit] never mind ill look else where for help
http://www.youtube.com/watch?v=X3QO0ffg2Tc&feature=related
ok the toturial looks like it will work but when he types in this line in his app.java
public boolean onCreateOptionsMenu(Menu menu) {
Click to expand...
Click to collapse
it is under lined with an error on his screen as well as mine and then he says he is importing the missing classes and the error just disappeas with no demonstrations of what missing classing or what key combination he used to import them...
http://www.google.com/#hl=en&q=impo...=f&aqi=&aql=&oq=&gs_rfai=&fp=d059ab474882bfe2
WOO HOO found what he left out...
Compiled and installed...
Boo hoo menu key does nothing!! time to go back through the other menu tutorials and see if i cant get it working now that i know of this hot key..
Went back to this toturial with the elusive import missing classes hotkey..
http://www.youtube.com/watch?v=6UYNnQOxCS8
It worked like a charm
just had to remove
newGame();
and
quit();
and i have buttons that do nothing so far
More missing pieces.
I created a new activity as shown to me in previous tutorials giving it its own seperate XML file in the res/layouts as well as a jave file and I made sure it is calling for the right layout.
I also added the activity in the androidmanifest as shown to me as well..
off this site
http://developer.android.com/guide/topics/ui/menus.html
I've taken the code to create menus.. ( i got it working )
I then followed this and made the changes
Set an intent for a single menu item
If you want to offer a specific menu item that launches a new Activity, then you can specifically define an Intent for the menu item with the setIntent() method.
For example, inside the onCreateOptionsMenu() method, you can define a new menu item with an Intent like this:
MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID, 0, "Select Photo");
menuItem.setIntent(new Intent(this, PhotoPicker.class));
Android will automatically launch the Activity when the item is selected.
Note: This will not return a result to your Activity. If you wish to be returned a result, then do not use setIntent(). Instead, handle the selection as usual in the onOptionsMenuItemSelected() or onContextMenuItemSelected() callback and call startActivityForResult().
Click to expand...
Click to collapse
It doesn't work... I don't understand why the intent would be in the onCreateOptionsMenu... it doesn't seem to work so I tried the alternative and replaced setIntent with with startActivityForResult.. and then I noticed it says "As usual" in the onOptionsMenuItemSelected()... which is where I would think the code would belong in the first place... but when I originally failed and tried to move the code there it errors...
Is ever step of the way really going to be half assed instructions.. i was beginning to think I had the hang of this.
Are the instructions bad or am i missing something???
Guess ill go dig in my hello android book.
EDIT: Wow that helped
startActivity(new Intent(this, register.class));
Click to expand...
Click to collapse
guess that book is worth something after all...
guess im just intending to start an activity with a particular intent and setting an intent alone isn't going to start the activity.... i suppose there must be some purpose behind setting an intent as they had describe on the google page.. just not seeing it yet...
Got to what i wanted tho.

[Q] Making an alternatice UI menu (like for example: the camera menu)

I am trying to create a more appealing menu for my application, however I am unsure as how to re-root the input of the menu button so that it makes certain images in the corners visible, (they are all in the same xml file, however just set to "invisible" by default. If also possible I'd like to activate this menu by just touching the screen, does anyone have any advice on how to do this?
If you need any more information please just ask
Thank you
You'll need to capture the menu button click. This might help:
http://stackoverflow.com/questions/4239880/detecting-physical-menu-key-press-in-android
For touching the screen you'll need an onTouch event for the view.
Sent from my HTC Desire using XDA App
thanks
but i am still unsure as how to identify the xml object and then change it's visibility in java
image:
Code:
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/menu_bottom_left"
android:id="@+id/bl"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:visibility="invisible"></ImageView>
using the physical keycode:
Code:
public boolean onKeyUp(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_MENU)
{
}
return true;
}
sorry but i am not that familiar with java
OK.
// Create an ImageView and assign it to your bl ImageView
Imageview bl= (ImageView)findViewById(R.id.bl);
// Change the visibility (VISIBLE = Visible, INVISIBLE = Invisible but takes up the same space in layout
// GONE = Invisible and does not take up space in layout)
bl.setVisibility(ImageView.VISIBLE);
Hope this helps

[Q] How to keep layouts inflated after activity restarts

Hi guys,
On a button click I am inflating a layout like so:
Code:
public void plusLayout(View v) {
// inflating layout here:
LinearLayout ll1 = (LinearLayout) findViewById(R.id.main_layout);
// this layout is being inflated:
View newView = getLayoutInflater().inflate(R.layout.layout_to_be_added, null);
// add layout
ll1.addView(newView);
}
But when the activity restarts, the inflated layouts are gone.
I'd like the layouts to stay there.
(The user can click a button to remove the layout by hand).
I must be missing something trivial here right?
Cheers,
Daan
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
nikwen said:
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
Click to expand...
Click to collapse
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
DaanJordaan said:
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
Click to expand...
Click to collapse
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
If it is, 2 ways I can think of :
Overriding savedInstanceState() & onRestoreInstanceState() :
First, declare a private Boolean before the onCreate() of your activity :
Code:
private Boolean isInflated = false;
Then, set it to true in the onClick() of your button, and override savedInstanceState and onRestoreInstanceState like so :
Code:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save state changes to the savedInstanceState.
// This bundle will be passed to onCreate if th activity is
// killed and restarted.
savedInstanceState.putBoolean("inflate", isInflated);
}
Code:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
Boolean myBoolean = savedInstanceState.getBoolean("inflate");
if (myBoolean == true)
plusLayout(myView);
}
Using the sharedPreferences
Same logic, different way to save the boolean :
Before onCreate(), declare a private boolean and a private SharedPreferences :
Code:
private Boolean isInflated = false;
private SharedPreferences prefs = getSharedPreferences("MY_PREFS");
in the onClick of your button :
Code:
isInflated = true;
Editor e = prefs.edit();
e.putBoolean("inflate", isInflated);
e.commit();
Then, in your onCreate(), retrieve the stored value and if it's true, call your plusLayout() method :
Code:
Boolean doInflate = prefs.getBoolean("inflate", false // this is the default value);
if (doInflate == true)
plusLayout(myView);
nikwen said:
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Click to expand...
Click to collapse
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
Androguide.fr said:
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
Click to expand...
Click to collapse
That is correct. Big thanks for the examples.
DaanJordaan said:
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
That is correct. Big thanks for the examples.
Click to expand...
Click to collapse
I would use his snippets. They are good (as always). Decide which one to use by what I have given above:
Just for turning:
onSaveInstanceState and onRestoreSavedInstanceState
For turning and reopening:
Shared preferences

How do you make buttons

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

[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