Button click change textview - java

I want to make a simple counter program where I have a Textview and two buttons, one with + another with - whichever I press I get 1 incremented or decremented.
My problem is that I want the Textview to update a variable and not text. (By that I mean I get the app to work with .setText("counter:"+ var_counter) but doesn't work with .setText(var_counter).
var_counter is an int.
final TextView tvContador = (TextView)findViewById(R.id.tvContador);
Button add = (Button)findViewById(R.id.bMais);
Button sub = (Button)findViewById(R.id.bMenos);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contador++;
tvContador.setText(getText(contador));
}
});
p.s: my string is a resource string.

Since var_counter is an int, setText(var_counter) tries to set the text of the widget to the string resource with such value as its id. What you want is:
setText(Integer.toString(var_counter));

use
.setText(Integer.toString(var_counter));

Simply:
.setText(""+var_counter);

Related

android - java get id of the item just clicked without set "onClick" to the item

How do I get an item id when I click on it without setting an "onClick" event in the xmk file?
I tried that:
private View.OnClickListener globalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int clickedPosition = (int) v.getTag();
// do something with position
}
}
But i don't understand how to use it
Hello!
Rebuild the method as follows:
private View.OnClickListener globalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}
Well, to get the target ID that you click, it is better to first define the attribute android:tag="target_id" in the XML file, and then access it within the called method when the target is clicked, using the v.getTag(). Of course, you can also get the clicked ID via v.getId() without doing so. You can check the ID from:
use if (v.getTag () == R.id.target_id), or parse it as follows:
String viewID = getResources (). GetResourceName (v.getId ())
Your code creates a listener without actually attaching it to anything, so it never receives click events. If you have, for example, a button that you want to respond to clicks, you can register your listener with it like so:
button.setOnClickListener(globalClickListener);

Android - automatically finding and making a setOnClickListener for every button

I have dozens of buttons, each of which I want to do the following for:
Button abcdefg = (Button) this.findViewById(R.id.abcdefg);
abcdefg.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
audiotoplay = "abcdefg";
playAudio(audiotoplay);
}
});
In this case is there a simpler way to do this for every button than copying and pasting this code block for every button and just replacing abcdefg with each buttons ID?
In strings.xml create a string array containing as strings the ids of the buttons, like:
<string-array name="buttonids">
<item>abc</item>
<item>def</item>
<item>ghi</item>
</string-array>
and then in your activity, get this array and for each string id get the integer id of the button with getIdentifier().
Then by findViewById() get a reference to each button and set the listener:
String[] buttonids = getResources().getStringArray(R.array.buttonids);
for (String buttonid : buttonids) {
final String name = buttonid;
int id = getResources().getIdentifier(name, "id", getPackageName());
Button button = findViewById(id);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audiotoplay = name;
playAudio(audiotoplay);
}
});
}
I assume that as in your sample code, you will assign the string id of each button to the variable audiotoplay.
If you add or remove buttons in your app, the only change you have to do is add or remove its string id from the array in strings.xml.
You can try butterknife, https://github.com/JakeWharton/butterknife
#OnClick(R.id.submit1)
#OnClick(R.id.submit2)
#OnClick(R.id.submit3)
#OnClick(R.id.submit4)
void submit() {
// Clicked ...
}
You can always create a class that extends from Button and define that specific behaviour there. After that you need to update your layout .xml to use your new class instead of the default one.
I'm not sure about the use case - but if you need the id you can save that as the button tag and then access it from OnClick.
For example:
public class YourButtonClass extends AppCompatButton {
....
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
audiotoplay = getTag();
playAudio(audiotoplay);
}
});
}
}
in your activity/ fragment:
findViewById<YourButtonClass>(R.id.btn_your_button).setTag("123")
and on your layout:
<this.is.your.package.name.YourButtonClass
android:id="#+id/btn_your_button"
...
/>
The simplest way would be to use tags. Each button in the layout xml should have
android:onClick="buttonClick"
android:tag="abcd1234"
Then you should have a single function in your Activity
public void buttonClick(View v) {
audiotoplay = v.getTag();
playAudio(audiotoplay);
}
You do not have to call any setOnClickListener, as it is set in the xml. Just make sure the buttonClick method is in your Activity class, not Fragment class. You can call it any name you like, I just used buttonClick to differentiate from any other onClick. If you must have it in Fragment, then you would assign a single onClickListener to a variable (or have the Fragment implement onClickListener) with same code, and call setOnClickListener on all buttons to it.

How can i stop sending messages which are sending in loop on click of an button in android

I want to know how can I stop message sending in a loop.
When I press stop, messages are still sent.
I have provided a stop() method.
for (i = 0; i < copy; i++) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if(stop!=1)
sms.sendTextMessage(number,null,message,sentPIn,pdelint);
}
}, 25000);
stop method
int stop=0;
public void st(View view){
Button b=(Button)findViewById(R.id.button2);
b.setText("Stopped");
stop=1;
}
Modify St function to this
public void st() {
Button b = (Button) findViewById(R.id.button);
#Override
b.setOnClickListener(new View.OnClickListener() {
b.setText("Stopped!");
stop=1;
});
}
The problem was u were not using an listener to detect button press. It is not advisable to change the button text use a text view instead!
Most likely he has set onClick attribute in the xml, although only he'll be able to clarify that.
I'm saying that because I see View as a parameter in the method st(View v).
Although if the attribute onClick is not set in xml #Audi 's solution would be good. Though on the contrary if the attribute has been set in the xml then
you should check if view.getId() == R.id.button then apply a button cast to your view and set its text to "Stopped".

Algorithm for my project in android

I have a android project that generates random numbers as the button's text. If you click a button the value of the corresponding button should be displayed in the edittext.
I am already getting the value of the buttons and also able to display it in the edittext. I have 12 buttons and 2 edittexts. What I want is, if I will do the first click then first value will display in the first edittext and in the second click the value will display in the second edittext.
My problem is that in the first click the value is getting displayed in the 2 edittexts simultaneously. Hope you can help me, here is my code:
b1=(Button)findViewById(R.id.b1);
et1=(EditText)findViewById(R.id.first);
et2=(EditText)findViewById(R.id.second);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str=((Button)v).getText().toString();
et1.setText(str);
et2.setText(str);
}
});
b1 = one of the buttons.
et1 and et2= the two edittexts.
str = empty string
That doesn't surprise me. You don't distinguish your cases within your onClickListener.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str=((Button)v).getText().toString();
// Check which edit text
if(isFirstClick()) {
et1.setText(str);
setFirstClick(false);
} else {
et2.setText(str);
}
}
});
See the 'isFirstClick()' like some kind of pseudo code, maybe you can also check if your first editbox is still empty or something like that.
Both #Averroes and #Sambuca have provided a smiliar solution which should work:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str=((Button)v).getText().toString();
if((et1.getText().toString()).equals(""))
et1.setText(str);
else
et2.setText(str);
}
});
In case you can do more than 2 clicks and your requirement is to output to textBox1 on odd clisk and Textbox2 on even click - use a boolean variable.

I am a beginner to Android App Dev: I am getting a force close all the time

I have recently just started learning how to develop android applications. I am am fairly proficient in Java, but I am still trying to get the hang of Android and xml stuffs.
So, thanks for the help in advance:D!
Right now, I am just trying to create an application that has an EditText widget and a button. Currently, all my code does is create an OnClickListener for the button, and define the OnClick method. I have no idea why it is force closing. I have experimented with a few small programs before(mainly experimenting with buttons), and I have also had this problem a few times, so I don't think it is unique to this code.
Here is the code:
public class AdditionActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(AdditionActivity.this, "Welcome to Addition Helper!", Toast.LENGTH_SHORT).show();
final EditText answerBox = (EditText) findViewById(R.id.answerBox);
final Button button = (Button) findViewById(R.id.button);
final TextView problem = (TextView) findViewById(R.id.problem);
//
//problem.setText("5+4");
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(AdditionActivity.this, "Started", Toast.LENGTH_SHORT);
String temp = problem.getText().subSequence(0, 1).toString();
int first = Integer.parseInt(temp);
temp = problem.getText().subSequence(2,3).toString();
int second = Integer.parseInt(temp);
int answer = first + second;
if(Integer.parseInt(answerBox.getText().toString()) == answer)
Toast.makeText(AdditionActivity.this, "Correct!!!!!", Toast.LENGTH_SHORT);
else
Toast.makeText(AdditionActivity.this, "WRONG", Toast.LENGTH_SHORT);
}
});
}
}
So if anyone knows why a beginner might be getting frequent force closes or if I am doing something wrong with my code, that would be GREAT! In my layout xml file, all I have are the EditText widget, the TextView widget, and the button.
Thanks again for your time, I really appreciate it.
I suppose your scenario is type in 1 + 1 in EditText, press button and get result shown in TextView. hence,
This is wrong: EditText answerBox and TextView problem
This is correct: EditText problem and TextView answerBox
force close is mostly due to NullPointerException or ArrayIndexOutofBoundException from this line:
String temp = problem.getText().subSequence(0, 1).toString();

Categories