Can a switch case do something like this? - java

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).

Related

Java - Efficient method with multiple onClickListener

My app currently has 5 buttons (I'm going to add more later) and when each button is clicked, it'll assign a number to an item.
I'm wondering if there's a more efficient way of writing the setOnClickListner (it seems like I have to use that since I'm using this as a fragment. I found a way to do it if I was to assign an onClick in the xml but I can't apply that to this part of the code). I have it written out 5 times (and in the future it'll be more)
buttons[0] = (Button) view.findViewById(R.id.cut1Btn);
buttons[1] = (Button) view.findViewById(R.id.cut2Btn);
buttons[2] = (Button) view.findViewById(R.id.cut3Btn);
buttons[3] = (Button) view.findViewById(R.id.cut4Btn);
buttons[4] = (Button) view.findViewById(R.id.cut5Btn);
buttons[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 1",Toast.LENGTH_SHORT).show();
data = 1;
}
});
buttons[1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 2",Toast.LENGTH_SHORT).show();
data = 2;
}
});
buttons[2].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 3",Toast.LENGTH_SHORT).show();
data = 3;
}
});
buttons[3].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 4",Toast.LENGTH_SHORT).show();
data = 4;
}
});
buttons[4].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 5",Toast.LENGTH_SHORT).show();
data = 5;
}
});
Could I maybe do a switch or a loop? Like assign i = 0, i < 5, i++ for the button array and then for data make that data = i + 1 ? If so, any suggestions on how I can do that?
Thanks!
THe other answers here will work, but either use the tag (generally a bad idea and prevents any other use) and aren't really object oriented. Instead you should make a class an instantiate it.
private class MyClickListener {
private int data;
public MyClickListener(int data) {
this.data = data;
}
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK" + data,Toast.LENGTH_SHORT).show();
}
}
...
int i=0;
for(Button button : buttons) {
button.setOnClickListener(new MyClickListener(i++));
}
You could use a common method and then implement a switch case based upon R.id of your button
An example would in like this.
in onCreate(--) method
cut1Btn = (Button) view.findViewById(R.id.cut1Btn);
cut2Btn = (Button) view.findViewById(R.id.cut2Btn);
cut3Btn = (Button) view.findViewById(R.id.cut3Btn);
cut4Btn = (Button) view.findViewById(R.id.cut4Btn);
cut5Btn = (Button) view.findViewById(R.id.cut5Btn);
cut1Btn.setOnClickListener(this);
cut2Btn.setOnClickListener(this);
cut3Btn.setOnClickListener(this);
cut4Btn.setOnClickListener(this);
cut5Btn.setOnClickListener(this);
Implement View.onClickListener in your activity and override this method in your activity
public void onClick(View v){
switch(v.getId()){
case R.id.cut1Btn:
//Put Your Code Here
break;
case R.id.cut2Btn:
//Put Your Code Here
break;
case R.id.cut3Btn:
//Put Your Code Here
break;
case R.id.cut4Btn:
//Put Your Code Here
break;
case R.id.cut5Btn:
//Put Your Code Here
break;
}
}
You can implement a switch to do this things:
Your class must implement OnClickListener and override function OnClick(View view).
Then just set OnClickListener(this) like this on onCreate method
buttons[1].setOnClickListener(this)
buttons[2].setOnClickListener(this)
buttons[3].setOnClickListener(this)
do a switch-case on override function
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// button 1 do
break;
case R.id.button2:
// button 2 do
break;
case R.id.button3:
// button 3 do
break;
}
}

Button long click does not work

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
}
}

Buttons outside the onCreate

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!

clearing different edittexts with different buttons while reusing same code

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

Creating switch case onClickListener for TextView

I've just started out in Java programming and am having a bit of trouble implementing an OnClickListener switch case for my clickable TextViews. I've managed to make a switch case for menu items, but i'm obviously not understanding it enough to make a more general case.
Here's the bits of my code that are important to it
public class MyActivity extends Activity implements SensorEventListener {
TextView tv, tv1, tv2, tv3;
#Override
public void onCreate(Bundle savedInstanceState) {
//get textviews
tv = (TextView) findViewById(R.id.xval);
tv1 = (TextView) findViewById(R.id.yval);
tv2 = (TextView) findViewById(R.id.zval);
tv3 = (TextView) findViewById(R.id.scalar);
And then I setup individual on click listeners for each TextView, e.g.
tv1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do things
}
}
});
But i'm trying to set it up so i have a a combined OnClickListener, like:
#Override
public boolean onClickListener (View v) {
switch (tv.findViewById()) {
case tv:
//Do things
return true;
case tv1:
//Do things
return true;
case tv2:
//Do things
return true;
case tv3:
//Do things
return true;
}}
I'm aware that code is very wrong, but i can't seem to wrap my head around it. I've already assigned my findViewById so i'm not sure what else to put into the switch!
Thankyou!
I'll provide an alternative answer. First you have to create an OnClickListener, which will receive your OnClick events:
OnClickListener listener = new OnClickListener()
{
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.xval:
//code
break;
case R.id.yval:
//code
break;
case R.id.zval:
//code
break;
case R.id.scalar:
//code
break;
default:
break;
}
}
};
Then, you have to associate that listener to every TextView you have:
tv.setOnClickListener(listener);
tv1.setOnClickListener(listener);
tv2.setOnClickListener(listener);
tv3.setOnClickListener(listener);
Once you click one of the TextViews, your OnclickListener onClick() callback will be called and it will check the TextView id you have clicked and run the code accordingly, dependeing on the case.
tv.setOnClickListener(this);
tv1.setOnClickListener(this);
tv2.setOnClickListener(this);
tv3.setOnClickListener(this);
#Override
public boolean onClick (View v) {
switch (v.getId()) {
case R.id.xval:
//Do things
return true;
case R.id.yval:
//Do things
return true;
case R.id.zval:
//Do things
return true;
case R.id.scalar:
//Do things
return true;
}}
Create one listener, add it to all TextView. Switch on the view id, which is a simple int
View.OnClickListener listener = new View.OnClickListener()
{
public void onClick(View v)
{
switch (v.getId()) {
case R.id.xval:
//Do things
return true;
case R.id.yval:
//Do things
return true;
case R.id.zval:
//Do things
return true;
case R.id.scalar:
//Do things
return true;
}
}
};
tv.setOnClickListener(listener);
tv1.setOnClickListener(listener);
tv2.setOnClickListener(listener);
tv3.setOnClickListener(listener);

Categories

Resources