Using a switch statement onClick to add a character to a EditText - java

I am trying to reduce the amount of code I have by making everything more efficient
I want to implement a switch statement instead of a long if statement
here is the switch i have began creating
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonA:
displayLetters(v);
break;
case R.id.buttonB:
displayLetters(v);
break;
and here is the displayLetters method that I want each case to run
private void displayLetters(View v) {
NewDisplayWord = EditText.getText().toString();
NewDisplayWord = NewDisplayWord + v.getTag();
EditText.setText(NewDisplayWord);
}
However instead of displaying A or B in the textedit when I press the buttons, I get null when I press any of the buttons

It seems that you are trying to get the text from the EditText by doing EditText.getText(). I think what you mean to do is use the v variable passed into displayLetters(). You can do something like this:
private void displayLetters(View v) {
NewDisplayWord = ((EditText)v).getText().toString();
NewDisplayWord = NewDisplayWord + v.getTag();// I do not know what is the use of `getTag()` here...
((EditText)v).setText(NewDisplayWord);
}
If the displayLetters() will only deal with EditTexts, you can make its parameter be an EditText

First, let's change displayLetters to accept String
private void displayLetters(final String letter) {
newDisplayWord = editText.getText().toString();
newDisplayWord = newDisplayWord + letter;
editText.setText(newDisplayWord);
}
Then call displayLetters() with String param:
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonA:
displayLetters(v.getTag());
break;
case R.id.buttonB:
displayLetters(v.getTag());
break;
default:
break;
}
}
If your onClick() listener will serve only the buttons, you could probably simplify it even further:
#Override
public void onClick(View v) {
//cast view to button
Button bt = (Button) v;
//get text from button
final String letter = bt.getText().toString();
//pass it to displayLetters()
displayLetters(letter);
}
Please follow Java naming convention, that is variable names start with lowercase. Also, I'm assuming that you have properly set your button and editText:
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);

Related

I am not allowed to pass a string from resource file within a switch case [Android]

I have few buttons and I have the following click listener for the same:
private View.OnClickListener onclick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.home:
break;
case R.id.contact:
break;
case R.id.terms:
break;
case R.id.touch:
show(R.string.about_us); //Error here
break;
}
}
};
On each button click I display the same popup, only the text differs. I have text in strings.xml file
below is my dialog function:
public void show(String message){
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.terms);
//dialog.setTitle("Terms & Conditions");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText(message);
text.setTypeface(helv_light);
ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.button1);
// dialogButton.setTypeface(helv_light);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
in case R.id.touch: My IDE complains with the following message:
show(java.lang.string) cannot be applied to (int).
If I replace show(R.string.about_us); with show(""+R.string.about_us); The error goes away, what do I miss here?
Use getResources().getString for getting string from strings.xml :
show(v.getContext().getResources().getString(R.string.about_us));
R.string.about_us is an int value, is not a string. To keep both you can overload show, providing the integer parameter, and call
public void show(final int messageId) {
sendMessage(getResources().getString(messageId));
}
The R.string.* values are ints. You need to use getResources().getString(R.string.str_id) to get the actual string value.

Event get String from 2 buttons

I am using an Adapter to generate buttons in a GridView.
Using an OnClickListener, whenever I click a button from the GridView, it is possible to get the String of the button in a variable. However, I want to click a button, store its text in a variable, then click a different button, store its text in another variable so later I can compare the two texts. How could I do that?
gI'm using OnClickListener, therefore my previous implementation for one button was the following:
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText.toString();
With this approach, I can only get and store text from first button clicked, unless I store all the values in an array.
Ok so from what I can understand, you want to compare the strings of the two items in a grid view. If this is what you want, heres how I would do it(just a psuedocode):
String mValue1, mValue2;
boolean isOneClicked = false;
onItemClickedListener(item, position){
if(!isOneClicked){
mValue1 = item.stringValue;
isOneClicked = true;
}
else{
mValue2 = item.stringValue;
//do whatever you want here
//Reset when done
mValue1 = "";
mValue2 = "";
isOneClicked = false;
}
}
Please you can share your code to turn the things more comprehensible? Edit your question please... Anyways:
MainActivity.java
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private String butString, butString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString = (String) button1.getText();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString2 = (String) button1.getText();
}
});
}
}
After that you can compare the two strings.

Pass method as parameter in Java to assign Listeners to multiple Buttons

I'm new to Java (coming from Python) and I'm trying to pass a method as a parameter in order to convert this code:
Button button1;
Button button2;
...
Button buttonN;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button1(v);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button2(v);
}
});
(...)
buttonN = (...)
To something like:
public AssignListener( integer tButton, Method tMethod )
{
button_view = (Button) findViewById(tButton);
button_view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
tMethod(view);
}
}
}
(...)
AssignListener( R.id.button1, onClick_button1 );
AssignListener( R.id.button2, onClick_button2 );
(...)
AssignListener( R.id.buttonN, onClick_buttonN );
I've read that you can't pass methods to functions, and some advice to wrap my function using Runnable to achieve this.
I have not clear idea about how to do it. Any idea on how do it easily? :?
Thanks.
EDIT: Should I wrap "AssignListener" in its own class and pass the class itself? :?
You can call findViewById() and seOnClickListener into onCreate method, and OnClickListenet outside the onCreate.
Button button1 = (Button)findViewById(R.id.button1);
or
findViewById(R.id.button1).seOnClickListener(mClickListener);
findViewById(R.id.button2).seOnClickListener(mClickListener);
findViewById(R.id.button3).seOnClickListener(mClickListener);
findViewById(R.id.button4).seOnClickListener(mClickListener);
private OnClickListener mClickListener = new View.OnClickListener(
public void onClick(View view){
switch(view.getId()){
case R.id.button1:
//button1 click handle here...
break;
case R.id.button2:
//button2 click handle here...
break;
case R.id.button3:
//button3 click handle here...
break;
case R.id.button4:
//button4 click handle here...
break;
}
});
Try it, hope it will helpful to you.
You could define and pass an onClickListener like this:
public AssignListener( integer tButton, OnClickListener listener ){
tButton.setOnClickListener(listener);
}
The simplest way is to create listener implementation for each button, as is written in your first snippet.
I don't see any reasonable benefit of having universal method like AssignListener(). Don't reinvent bicycle, use existing setOnClickListener() method and pass listener specific for button.
An easy solution would be to create a function called tMethod that takes a button id, and has a switch statement that allows for a certain action to be performed for the given button id. This would then be called inside the onClick function like tMethod(view.getId()).
Btw, Python has methods. Java has functions. Pedant mode turned off!
public class MyClass implements OnClickListener, OnLongClickListener {
Button button1;
Button button2;
...
Button buttonN;
. . .
setButtonsListener(findViewById(<your top view id>));
. . .
void setButtonsListener(ViewGroup vg) {
int count = vg.getChildCount();
Button btn;
View v;
for(int i=0; i < count ; i++) {
v = vg.getChildAt(i);
if( v instanceof Button ) {
btn = (Button)v;
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
} else if( v instanceof ViewGroup ) {
setButtonsListener((ViewGroup) v);
}
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}

comparing array of strings to one string in android?

when clicking on the button it does nothing ,,,after testing I concluded the problem is with the equal method statment ,,,the whole issue is when comparing string array to string any solutions?
EditText coderead = (EditText)findViewById(R.id.editText1);
Button go = (Button)findViewById(R.id.button1);
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
final double pointx[] ={23.666666,65.22222};
final double pointy[] ={31.55555,29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
for (int i=0; i<code.length; i++) {
if(code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
}
else{Toast.makeText(getBaseContext(), "code not found", 5000);}
}
}
});
Your mn variable should be read after your button has been clicked.
Button go = (Button) findViewById(R.id.button1);
final String code[] = {"m1", "n2"};
final double pointx[] = {23.666666, 65.22222};
final double pointy[] = {31.55555, 29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
// mn should be read after the button click!
EditText coderead = (EditText) findViewById(R.id.editText1);
final String mn = coderead.getText().toString();
for (int i = 0; i < code.length; i++) {
if (code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
} else {
Toast.makeText(getBaseContext(), "code not found", 5000);
}
}
}
});
So if I understand your code correctly you are trying to respond to a button click and take the text that has been input and do something based on that?
You are setting the value of mn at the time you are creating the button, rather than when the button is pressed. At that time the text will be empty (or null). You should move the code to get the value of the entered text to within the onClickListener.
Should your "code not found" message happen outside the for loop?
What do you mean by nothing happens? Do you get a Toast message or not? Did you make sure that no error is being generated? If you are not getting the Toast Message and you have no errors, then make sure the intent is correct. I would recommend you debug the code from the line of Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
Then, report what is happening back here.
Something I don't get. With these two lines:
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
Why don't you just compute the (final) index to code right then and there, vs waiting until onClick?

Increase value of TextView e.g. 0 as clicked value +1

I am developing my program but it seems It really giving me hard time regarding TextView.XD
Just like in Scoreboard. Increasing the value of score as you click the TextView assigned to it.
This is my code:
private OnClickListener mHscoreListener = new OnClickListener() {
public void onClick(View v) {
//DO INCREASE
h1++;
TextView HScore = (TextView) findViewById(R.id.hscore);
HScore.setText(h1);
};
};
The above code not working and I don't know why.
I think you should set onClickListener to TextView HScore.
Try this way
Define HScore and h1 as class variable.
HScore = (TextView) findViewById(R.id.hscore);
OnClickListener mHscoreListener = new OnClickListener()
{
public void onClick(View v)
{
// DO INCREASE
h1++;
HScore.setText(h1 + "");
};
};
HScore.setOnClickListener(mHscoreListener);
What type is h1?
You may need to use h1.toString()
private OnClickListener mHscoreListener = new OnClickListener() {
public void onClick(View v) {
//DO INCREASE
h1++;
TextView HScore = (TextView) findViewById(R.id.hscore);
HScore.setText(h1.toString());
};
};

Categories