android toggle button state set texview text - android

i have a toggle button which when set to the on position sets the hint to one of my textview to
"kg"
.
the initial hint of the text view is
"st"
which should be shown if the toggle is in the off position.
when i first start the app the textview dispalys
"st"
(which at first is ok as the toggle is in the off position) now when i press the toggle it turns to the on position and displays
"kg"
in the textView (this is also ok.)
now comes the problem. if i click on the toggle again (off position) the textView stays as
"kg"
does anyone know how i could set it to always display "st in the off state and "kg" in the on state.
many thanks in advance
addListenerOnButton();
}
public void addListenerOnButton() {
unitToggle = (Button) findViewById(R.id.unitToggle);
final TextView tw1 = (TextView)findViewById(R.id.tw1);
unitToggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
tw1.setHint("kg");

unitToggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
if(tw1.getHint().toString().equals("kg"))
tw1.setHint("st");
else
tw1.setHint("kg");

The main reason for the said problem is the logic which has not yet been implemented.
When you click the button for the first time it sets the text to "kg" which it will set always on any number of click. since you have written the statement
tw1.setHint("kg");
inside your onClick() method without keeping the state of the button. emphasized text.
In order to make it correct use a boolean flag and change its state on each click and set the text based on the flag value.
The best way to do it is to use ToggleButton which has the inbuilt on/off states so you don't need to have your on boolean flag and set the hint based on the button state.

Try
private boolean on=false;
unitToggle.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer result = new StringBuffer();
if(on){
tw1.setHint("kg");
on = true;
}else{
tw1.setHint("st");
on = false;
}

Related

Android view isDirty inside onClick

I want to check if the text in some EditText is changed, after user clicks some Button. But View#isDirty seems not to return the correct state of the EditText if called inside onClick. For instance, I wrote something like this:
public class MainActivity extends Activity {
EditText editText;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.f);
editText = (EditText) findViewById(R.id.e);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println((editText.isDirty() ? "is dirty" : "is clean"));
}
});
}
}
before i make any change to the editText, it outputs is clean, as expected. But the same is clean is printed even after I write something in editText.
When will isDirty be called? And is it the correct way to do this at all?
Update:
I also want to check if some Switch and Spinner values are changed. Is isDirty() the correct way to do this?
By the time you click your button edittext is no longer dirty - text is already updated and view redrawn. Maybe if you change your onclick handler you will understand better what is going on.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText = (EditText) findViewById(R.id.e);
System.out.println((editText.isDirty() ? "is dirty" : "is clean"));
}
});
isDirty will return true only as long as view has not been redrawn. This happens quite quickly and basically you do not have (and dont need) any control over this.
I think you need to use some other methods to achieve what you want.
I would suggest to use:
https://stackoverflow.com/a/9459848/5684335
The comment from Okas is a good explanation why.

Change button text over other button android

I create an application in android studio and I need advice, I got one button, and I need to change the text on the second button clicks through to the first. I have a code that changes only TextView but not the text on the button.
NewText = (TextView)findViewById(R.id.textView1);
ChangeText = (Button)findViewById(R.id.ch_txt_ger);
final TextView finalNewText1 = NewText;
ChangeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Set Text on button click via this function.
finalNewText1.setText(" (Frohe Weihnachten) ");
}
});
Same concept as you did for textView
Button SecondButton,ChangeText; // declaring the buttons
SecondButton = (Button)findViewById(R.id.button2);
ChangeText = (Button)findViewById(R.id.ch_txt_ger);
ChangeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This changes the text on the second button
SecondButton.setText("New Text Here");
}
});
SecondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do anything
}
});
Button ChangeText;
ChangeText = (Button)findViewById(R.id.ch_txt_ger);
ChangeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//part to change the button text
Button tmp_button = (Button)findViewById(R.id.ch_txt_ger);
tmp_button.setText("Frohe Weihnachten");
//part to change the textview text
TextView NewText
NewText = (TextView)findViewById(R.id.textView1);
finalNewText1.setText(" (Frohe Weihnachten) ");
}
});
After Clicking outlooking
Here you go: You can define a temporary button variable and make the change on it if setting the same button on its own clicking is causing problems.
And if the text will not change according to user, and if you know it like On/OFF, Red/Green you can also code it with a selector file which would make the java code look more clean.
A tiny advise: Defining the TextViews and Buttons that will get affected should all be written in the same function and close to the place where they are being changed for you to keep track of where you coded them.
I would add one thing, in case if you want to save the new button name when you close and reopen your app, you could use Shared Preferences: https://developer.android.com/training/basics/data-storage/shared-preferences.html

How can I change Text of Textview from other funcion?

this is my first question so I hope to make it clear.
I have one textView with some numerical text and next to it one button with one click listener and what I want is that when you click on the button the numerical value (>=0) of the TextView decrements in one.
Here is part of my code:
TextView Counter = new TextView(this);
if (intSeries != 0)
Counter.setText(Integer.toString(intSeries));
else
Counter.setText("0");
Counter.setId(4);
tablaContador.addView(Counter,Tr);
Button Done = new Button(this);
Done.setText("-1");
if (intSeries != 0)
Done.setVisibility(View.VISIBLE);
else
Done.setVisibility(View.GONE);
Done.setId(6);
Done.setOnClickListener(this);
And this is the onClick funcion (part of it):
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case 6:{
TextView text = (TextView)findViewById(4);
int series = Integer.parseInt(text.getText().toString());
series--;
text.setText(series);
if (series==0){
Button boton = (Button)findViewById(6);
boton.setVisibility(View.GONE);
}
}
}
}
The error is when I try to make the setText inside the onClick function, I hope it can be fixed or maybe recieve other idea to do it.
Thank you so much.
I would avoid all this hardcoding of Ids, use resources instead.
Your call to
text.setText(series)
is passing an int. The only valid setText(int resId) overload expects a resource associated with the int value, i.e. a string resource.
Convert your series value to a string.
Something like:
text.setText(Integer.toString(series));
You should setup series as an integer. And increase/descrease it as you wish. When you want to change the button's text convert the int to String.
Instead of:
text.setText(series);
use:
text.setText(String.valueOf(series));
Variablenames in java can't start with a capital letter. That is reserved for classnames.
Counter -> counter
Done -> done
I tried this and it worked:
//Create onClickListener
OnClickListener pickChoice = new OnClickListener()
{
public void onClick(View v)
{
TextView txt = (TextView) findViewById(4);
int number = Integer.valueOf(txt.getText().toString());
txt.setText(String.valueOf(number -1));
}
};
//Create layout
LinearLayout lnLayout = new LinearLayout(this);
lnLayout.setOrientation(LinearLayout.VERTICAL);
TextView txt = new TextView(this);
txt.setId(4);
txt.setText("0");
lnLayout.addView(txt);
Button Done = new Button(this);
Done.setText("-1");
Done.setId(6);
Done.setOnClickListener(pickChoice);
lnLayout.addView(Done);
setContentView(lnLayout);
Where are you creating your button inside? an activity? the part where you pass the onClickListener to the button doesn't make sense, maybe the button is getting a wrong listener and gets you an error every time you press the button ?
The code should be easy to understand, if there is anything you need me to explain please ask :)

Dynamically populate a button value android

I have seen lots of example to which one use a if condition or a case statement to programmatically change the conditions of elements...yadda yadda. I need to change the value of a button based on what the user clicks. Below is the code that I currently have.
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){CONTINUES TO OTHER FUNCTIONS }
I basically need to know what button was pressed. Then dynamically populate it into findViewById() function. i.e.
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
This way by the time it gets to the final Button part of the code it will have the value to which the user clicked on. Code works if I only want to have one button or a page mile deep in different configuration (not ideal).
All the examples I have seen so far are after the user clicks the button (which is what I want) but they name the buttons name statically like above code shows but very much static.
Hope that all makes sense.
UPDATE:
I think I may have confused the situation. Below is the remaining code. Hopefully this will provide context. The btnOpenPopup needs to remain the same as it's used in the call to execute the command for a new window to actually popup. Hopefully this will provide a bit more context for what I'm trying to achieve.
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.meditationpopup, null);
//set the title of the popup
TextView titletext = (TextView) popupView.findViewById(R.id.chakratitle);
titletext.setText(activityName);
if (activityName.equals("Root"))
{
switch (arg0.getId())
{
case R.id.color:
//Rename the string so to get the value from the string xml
String stringName = activityName.toLowerCase().replaceAll(" ","")+"color";
TextView desctext = (TextView) popupView.findViewById(R.id.popupDesc);
desctext.setText(getString(getStringResource(getApplicationContext(),stringName)));
break;
case R.id.polarity:
//Rename the string so to get the value from the string xml
String polarityString = activityName.toLowerCase().replaceAll(" ","")+"polarity";
TextView polarityDesc = (TextView) popupView.findViewById(R.id.popupDesc);
//polarityDesc.setText(activityName);
polarityDesc.setText(getString(getStringResource(getApplicationContext(),polarityString)));
break;
}
}
I think
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
should be
Button btnOpenPopupFirst = (Button)findViewById(R.id.polarity);
Button btnOpenPopupSecond = (Button) findViewById(R.id.color);
you should declare different different button for diffrerent findviewbyid
also in my eclipse it is not accepting
btnOpenPopup.setOnClickListener(new Button.OnClickListener()
instead it works with
btnOpenPopup.setOnClickListener(new View.OnClickListener() {}
and you need to provide more clear view of what you want to perform
new thoughts,try doing this:
btnOpenPopupFirst.setOnClickListener(this);
btnOpenPopupSecond.setOnClickListener(this);
then option will come on both the above code lines
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (MainActivity)
choose this
let MainActivity implement OnClickListener
then this option will come
The type MainActivity must implement the inherited abstract method View.OnClickListener.onClick(View)
choose
add unimplemented method
now
#Override
public void onClick(View v)
will be created
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.polarity:
Toast.makeText(getApplicationContext(), "btnOpenPopupFirst(polarity) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
break;
case R.id.color:
Toast.makeText(getApplicationContext(), "btnOpenPopupSecond(color) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
default:
break;
}
}
And post your views after implementing this way.
int[] id={R.id.button1,R.id.button2};
Button b=(Button)findViewById(id[i]);
The onClick method in Button.OnClickListener has a View parameter... you can call getId() on that view to get the id of that button that was clicked on.
It doesn't make too much sense to me. If what you really want is this:
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
All you need to do is set your value in the onClick(View view) method of your OnClickListener
public void onClick(View view) {
btnOpenPopup = (Button)view;
}

Modifiy text in a button - if statement

I am currently creating an android application with different options. One of the option would be to have a button that would show "Activate" as default. When the application would be running, clicking on it would change it to "Disable" and then to "activate" if clicked again. I believe that all I have to do is to .getText with a string variable then use this variable in a if statement but it seems like it is not reacting to any of my conditions...
final Button button = (Button) findViewById(R.id.bSensor);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String buttonText = button.getText().toString();
if (buttonText == "#string/Disable") {
button.setText(R.string.Enable);
}
else if (buttonText == "#string/Enable"){
button.setText(R.string.Disable);
}
}
});
Thanks for help
Phyzikk
You shouldn't use the == operator when comparing strings in Java. Source
You should either use the .equals() method of the string, or alternatively you could keep a global boolean state flag to determine which value is set. This way you won't need to do a string compare every time you need to figure out if it's active or disabled.
Use .equals to compare strings. You wont need the #String/ prefix as this is not part of what the button displays.
final Button button = (Button) findViewById(R.id.bSensor);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String buttonText = button.getText().toString();
if (buttonText.equals(getResources().getText(R.string.Disable)) {
button.setText(R.string.Enable);
}
else if (buttonText.equals(getResources().getText(R.string.Enable)){
button.setText(R.string.Disable);
}
}
});

Categories

Resources