I have two different edittext fields, each with a 'clear' button to clear the inputted text. I can clear both fields like so:
XML:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fieldOneInput"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/clearButtonText"
android:id="#+id/clearTextField1"
android:onClick="clearTextField1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fieldTwoInput"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/clearButtonText"
android:id="#+id/clearTextField2"
android:onClick="clearTextField2"/>
Java:
public void clearTextField1(View view){
EditText fieldOneInput = (EditText) findViewById(R.id.fieldOneInput);
fieldOneInput.setText("");
}
public void clearTextField2(View view){
EditText fieldTwoInput = (EditText) findViewById(R.id.fieldTwoInput);
fieldOneInput.setText("");
}
This isn't practical if I have multiple edittexts each with a 'clear' button. How would I go about clearing different edittexts fields using different buttons while reusing the same (java) code?
You can achieve this using following code:
public class AbcActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//... your code here, to get button objects from xml file
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
clearEditText(R.id.editText1);
break;
case R.id.button2:
clearEditText(R.id.editText2);
break;
case R.id.button3:
clearEditText(R.id.editText3);
break;
case R.id.button4:
clearEditText(R.id.editText4);
break;
}
}
private void clearEditText(int editTextId) {
findViewById(editTextId).setText("");
}
}
You can define a method like this:
private void setClickListener(Button button, final EditText editText) {
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
editText.setText("");
}
});
}
And then you can call
setClickListener(button1, editText1);
setClickListener(button2, editText2);
...
Note: Avoid calling findViewById(id) inside onClickListener, do it just one time before setting the listener.
Use this for every text field
public void clearTextField1(EditText editText){
editText.setText("");
}
You can use following code snipset to make code reusable
You have to call this method on button click. And pass edittext which you wants to clear and button on which you wants to clear edittext
public void clearOnClick(final EditText edtClear, Button btnClear)
{
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edtClear.setText("");
}
});
}
Well either way you still have to instantiate the buttons, this is obvious. One way that I can recycle my code and make it easy is I copy and paste a stock code, such as
public void clearTextField*(View view){
EditText* fieldOneInput = (EditText) findViewById(R.id.fieldOneInput*);
fieldOneInput*.setText("");
}
And then proceed to use Notepad++ (specifically the find and replace function to replace the "*" with whatever number textView you are on. Simple and effective. Besides this I suppose you could create a public void function similar to this and pass the id of the button into it like so:
public void ClearText(String id){
Button defaultButton = (Button)findViewById(id);
defaultbutton.setText("your text");
}
But I didn't test that code so don't fault me if there is an error or exception in there. Hope this helps!
First of all, whenever you feel like you need more than one click listeners for buttons,etc. in your class, just implement the interface View.OnClickListener.
Each view has a unique id that we assign to it. These ids are stored as compile time constants and hence can be referenced into a switch case.
Note: This approach does'nt work if you want to your code to be added as a module.
You can use answer by naran z and modify it a little.
#Override
public void onClick(View view) {
int id = INVALID_EDITTEXT_ID; // say -1
switch (view.getId()) {
case R.id.button1:
id = R.id.editText1;
break;
case R.id.button2:
id = R.id.editText2;
break;
case R.id.button3:
id = R.id.editText3;
break;
case R.id.button4:
id = R.id.editText4);
break;
}
if(id!=INVALID_EDITTEXT_ID)
findViewById(id).setText("");
}
Related
I'm trying to work on some code I did for a dice rolling app, where if the roll button was pressed it would display random dice sides.
I am trying to re-use this concept for my multiple choice quiz app, where if any button is pressed, right, or wrong, it will move on to the next question:
I was thinking it would look something like this, with "button" representing all buttons being pressed.
However in this multiple choice quiz there will only be 4 buttons (A, B, C and D) that I want to have cause this happen if pressed. I'm sure I could make this happen by repeating the paragraph of code 4 times with each button, but I was wondering if there was a simpler way to have all 4 buttons be represented on the same line
(A lot of the code I'm showing is meant to be for a dice app it's mainly the first word of the first line I want help with)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("multic", "the Button has been pressed!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(8);
Log.d("Dicee", "the random number is: " + number);
leftDice.setImageResource(diceArray[number]);
int number1 = randomNumberGenerator.nextInt(8);
rightDice.setImageResource(diceArray[number1]);
}
});
I expect that after one of the buttons is pressed it will move on to the next question.
You can define the listener like this:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("multic", "the Button has been pressed!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(8);
Log.d("Dicee", "the random number is: " + number);
leftDice.setImageResource(diceArray[number]);
int number1 = randomNumberGenerator.nextInt(8);
rightDice.setImageResource(diceArray[number1]);
}
};
and then set it to as many buttons as you want:
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
button4.setOnClickListener(listener);
You can use a single listener object with a switch statement to check which button is clicked.
Button b1,b2;
//findViews
View.OnClickListener listener=new View.OnClickListener() {
#Override
public void onClick(View v) {
//code
switch((Button)v){
case b1:
//code
break;
case b2:
//code
break;
}
//code
}
};
b1.setOnClickListener(listener);
b2.setOnClickListener(listener);
For a multiple choice quiz, with a set of 4 possible answers, I would suggest that you use a RadioGroup with constituent RadioButtom objects, like so:
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Notice how each RadioButton has the onClick attribute. You can name the same method for all radio buttons, and then in the activity or fragment use one method for all buttons with a switch statement, like so:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
To read more: https://developer.android.com/guide/topics/ui/controls/radiobutton#java
Multiple different choices as i am thinking it:
1)
Set android:onClick="onNextQuestion" on xml of all your buttons.
then in your java code write:
public void onNextQuestion(View view) {
// Do something in response to button click
}
2) (Better as can work in more cases) Make an NextQuestionClickListener class which will implement the interface View.OnClickListener and will implement the method onClick doing the code you wish.
class NextQuestionClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
// Do something in response to button click
}
}
Then set the listener to each button:
NextQuestionClickListener nextQuestionClickListener = new NextQuestionClickListener();
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
...
button1.setOnClickListener(nextQuestionClickListener);
button2.setOnClickListener(nextQuestionClickListener);
...
3) Using RxJava and RxBindings
RxView.clicks(button1)
.mergeWith(RxView.clicks(button2))
.mergeWith(RxView.clicks(button3))
.mergeWith(RxView.clicks(button4))
.subscribe(aVoid -> {
// Do something in response to button click
}, throwable -> Log.e(TAG, "error in handling click of next question", throwable));
4) Also i found butterknife where you can do:
#Onclick({R.id.button1,R.id.button2,R.id.button3,R.id.button4})
void onButtonClick(View aView) {
// Do something in response to button click
}
I'm working on a soundboard and I want to implement a long click to share the sound.
I am working with a switch Case for each button
public void MainMMP(View view){
switch (view.getId()) {
case R.id.button1:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx1);
MainMMP.start();
break;
case R.id.button2:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx2);
MainMMP.start();
break;
case R.id.button3:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx3);
MainMMP.start();
break;
And now I want to implement the long click. I tried a lot of different code here but it is not working for me.
I do not know where to put the onLongClick statement and how.
Can somebody show me a working method and in case of long click it should just send me a Toast that I know the method works?
You could add the OnLongClickListener where you want, in the onCreate method for example.
Try to use the following code:
Button button = (Button)findViewById(R.id.button);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Your code
return false; // True if you want to execute simple click code too
}
});
You can use this
private View.OnLongClickListener listener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
switch (view.getId())
case R.id.button1:
// Do something...
break;
case R.id.button2:
// Do something else...
break;
// If you still want to get normal click callbacks return true,
// if you do not then return false.
return true;
}
}
Somewhere in your code
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);
Or better this
One common recommended way to get onClick/onLongClick/whatever callbacks is to make the Activity implement the callback interfaces.
class YourActivity extend Activity implements View.OnLongClickListener {
#Override
public boolean onCreate(/* ... */) {
// ...
button1.setOnLongClickListener(this);
button2.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
// Same code as the one above
}
}
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!
My idea is that I have buttons on my app that leads to a single activity. I want it to have the same text template but different contents appearing when different buttons are clicked. I already have the XML file done, I got stuck on the code. I was thinking of using switch case but can it be possibly done with switch case? Or am I being too ambitious?
EDIT: Here's the code I have so far:
public class SelectKeys extends Activity {
private static final int[] buttonIDs = {R.id.cKey, R.id.cSharpKey, R.id.dKey, R.id.dSharpKey, R.id.eKey, R.id.fKey, R.id.fSharpKey, R.id.gKey, R.id.gSharpKey, R.id.aKey, R.id.aSharpKey, R.id.bKey};
private Button[] bt = new Button[buttonIDs.length];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_keys);
for (int i = 0; i < buttonIDs.length; i++) {
final int b = i;
bt[b] = (Button) findViewById(buttonIDs[i]); // Fetch the view id from array
bt[b].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opens up new screen
Intent intent = new Intent(getApplicationContext(), ChordKeys.class);
startActivity(intent);
}
});
}
}
public final void keyButton(final View v)
{
switch(v.getId())
{
case R.id.cKey:
{
setContentView(R.layout.activity_key_c);
break;
}
case R.id.cSharpKey:
{
setContentView(R.layout.activity_csharp_dflat);
break;
}
// adding more cases later once I get this to work
}
}
}
Of course it can be done with a switch case, you just need to create a class that implements onClickListener, and link all your buttons with this listener, like this:
final Button button= (Button) findViewById(R.id.button1);
button.setOnClickListener(new MyButtonListener());
class MyButtonListener implements View.OnClickListener{
#Override
public void onClick(View v) {
int id=v.getId();
switch (id){
case R.id.button1:
button.setText("Text1");
break;
case **:
break;
default:
break;
}
To have a centralized Click handler which can be addressed in your xml layout:
Add this method to your Java code
public final void clickHandler(final View v)
{
switch(v.getId())
{
case R.id.btn1:
{
// Do something, when you click btn1
break;
}
case R.id.btn2:
{
// Do something else, when you click btn2
break;
}
// ... more cases ...
}
}
In your xml layout:
...
<Button
android:id="#+id/btn1"
...
android:onClick="clickHandler"
/>
<Button
android:id="#+id/btn2"
...
android:onClick="clickHandler"
/>
...
Note (1): This is valid not only for Buttons, but also for ImageButtons, ImageViews, TextViews, ...
Note (2): You can use it with mixed Views at the same time (i.e.: a Button, 2 TextViews and an ImageView can all address the same clikHandler() method).
I'm new to android development, and haven't programmed GUI's in java yet so button work is all new to me.
I'm making a simple hello world app, has some buttons/radios/checkboxes etc. We have to figure out a way to make it nice, there is nothing specific in the brief. so I figured I'd get some buttons and show the different kinds of toast, maybe change the background etc.
so I implemented a toast based off a tutorial, but it works on all of the instantiated buttons instead of just the one I want. I would like the other button to do something else.
I think it has to do with the onClickListener, but beyond that I'm stuck.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(this);
btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener(this);
cb=(CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
browser=(WebView)findViewById(R.id.webkit);
browser.loadUrl("http://www.google.com/search");
}
public void onClick(View v) {
new AlertDialog.Builder(this).setTitle("MessageDemo").setMessage(
"This is an Alert Dialogue Toast").setNeutralButton(
"Here, here!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Toast.makeText(HelloWorldActivity.this,
"<clink, clink>", Toast.LENGTH_SHORT).show();
}
}).show();
}
and here's the xml for the buttons
<Button android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Testa"
android:layout_weight="0.2"></Button>
You've added the same onClickListener to each button so they will have the same behavior. You can actually create the listener right inside the setOnClickListener call, like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(this).setTitle("MessageDemo").setMessage(
"This is an Alert Dialogue Toast").setNeutralButton(
"Here, here!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Toast.makeText(HelloWorldActivity.this,
"<clink, clink>", Toast.LENGTH_SHORT).show();
}
}).show();
}
});
btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
// Do something different here.
}
});
// The rest of onCreate
}
EDIT: I've updated the answer to make it clear which parts of your original code would go where, but I usually wouldn't stick a big chunk of code like that inside of the onClick as it's not very readable. I'd prefer something more like this:
public void onCreate(Bundle savedInstanceState) {
// other onCreate code
btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
showBtn1ClickedDialog();
}
});
// other onCreate code
}
private void showBtn1ClickedDialog() {
new AlertDialog.Builder(this).setTitle("MessageDemo").setMessage(
"This is an Alert Dialogue Toast").setNeutralButton(
"Here, here!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Toast.makeText(HelloWorldActivity.this,"<clink, clink>", Toast.LENGTH_SHORT).show();
}
}).show();
}
In addition to goto10's solution, if you're not interested in defining the listeners in-line, your existing click handler can check the ID of the view:
public void onClick(View view) {
switch (view.getId()) {
case R.id.about_button:
// handle about
break;
// etc.
I tend towards goto10's solution, or even inner classes, rather than a switch statement like this, but it's another option. That said, I'm voting up his/her answer, and not mine.
One reason to use a switch instead of inner classes is memory usage, although with modern devices, this might not be a huge issue--but each inner class does take more space, and if the handler is small, IMO is more efficient to do it this way.
Clicking on any button generates an event which is caught by the onClick eventListener. But it doesn't automatically distinguish between the events as to which click generated the event. The information is contained in the View v and by using a switch case on the view, we can have separate events for different clicks.
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn1:
//Do something here
break;
case R.id.btn2:
//Do something else here
break;
case R.id.btn3:
break;
}
}
A summary of how you can use Listeners in your application.