i have a problem and i dont know how to fix it .I want to make a basic begginer calculator app.I want only one checkbox to be checkable at time but i cant figure out ,stil can check all .And how can i cast strings from edittext to doubl?.App is not finished yet .
Sorry for english.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.top_fragment);
double result ;
EditText number_1 = (EditText)findViewById(R.id.number_1);
EditText number_2 = (EditText)findViewById(R.id.number_2);
CheckBox add_box = (CheckBox)findViewById(R.id.add_box);
CheckBox subtract_box = (CheckBox)findViewById(R.id.subtract_box);
CheckBox divide_box = (CheckBox)findViewById(R.id.divide_box);
CheckBox product_box = (CheckBox)findViewById(R.id.product_box);
final Button button = (Button)findViewById(R.id.button);
number_1.getText().toString();
number_2.getText().toString();
if(add_box.isChecked())
{
subtract_box.setEnabled(false);
divide_box.setEnabled(false);
product_box.setEnabled(false);
}else if(subtract_box.isChecked())
{
product_box.setEnabled(false);
divide_box.setEnabled(false);
add_box.setEnabled(false);
}else if(divide_box.isChecked())
{
subtract_box.setEnabled(false);
product_box.setEnabled(false);
add_box.setEnabled(false);
}else if(product_box.isChecked())
{
subtract_box.setEnabled(false);
divide_box.setEnabled(false);
add_box.setEnabled(false);
}
}
}
you have to set a listener.
add_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Disable or enable what you want here. it will be called when add_box is checked or unchecked.
}
});
Do the same for each checkbox, disabling or enabling what you want.
To convert to String to Double you can do that:
Double value1 = Double.valueOf(number_1.getText().toString());
Make sure its not a null value and can be cast to a double.
You can use try / catch.
You may use RadioButton and RadioGroup instead of Checkboxes.
Radio buttons allow the user to select one option from a set. You should use radio buttons for optional sets that are mutually exclusive.
Official doc of RadioButton:
http://developer.android.com/guide/topics/ui/controls/radiobutton.html
Update:
To convert a String to Double you can do that:
// obtain a reference
EditText number_1 = (EditText)findViewById(R.id.number_1);
// obtain the string value
String number_1String = number_1.getText().toString()
// convert the string value to double value
Double number_1Double = Double.valueOf(number_1String);
Related
So I'm trying to learn Kotlin and have been using Android Studios to practice and learn. Currently I'm trying to make a simple activity with RadioGroup (with Radio Buttons), save the selected value, and then display how much of each value (radiobutton) was selected.
My question is, how do I print which button was selected, and how many of this type of button was selected?
I tried the following:
//in MainActivity.kt in my MainActivity class
s1RadioGroup.setOnCheckedChangeListener { _, checkedId ->
//if catButton was selected add 1 to variable cat
if(checkedId == R.id.catRadio) {
catSum += 1
print(catSum)
}
//if dogButton was selected add 1 to variable dog
if(checkedID == R.id.dogRadio) {
dogSum += 1
print(dogSum)
}
Not sure if I'm going about it the right way, but the desired output is:
I have layout, ID's, clear button, and everything else working. But I'm not sure how to use onClickListener event on 'SaveButton' to save selected radio button and then displaying results (Ex: Cat = 1, Dog =2). I would appreciate any suggestions, or if you can point me in the right direction.
You can maybe try something like this:
RadioButton rb = (RadioButton) findViewById(R.id.radio_button);
// restore previous state
rb.setChecked(lastButtonState);
// set a listener
rb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call this to enable editing of the shared preferences file
// in the event of a change
SharedPreferences.Editor editor = sharedpreferences.edit();
Boolean isChecked = rb.isChecked();
// use this to add the new state
editor.putBoolean(BUTTON_STATE, isChecked);
// save
editor.apply();
}
});
I realize that this is in Java, and you're asking for kotlin, but a SharedPreference, is what you would need to save the radio button's state.
if you want to save all datam you can use database or sharedprefrence.
and if you only want just display value is clicked, you can make like this in button save.
String result1 = ""
String result2 = ""
String result3 = ""
RadioGroup radioGroup = findViewById('yourRGidFromXml')
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton rb = findViewById(selecetedId)
result1= rb.getText.toString()
Log.i("ID", String.valueOf(selectedId));
}
});
//this just for see result
btnSave.OnclikListener(view -> {
Log.i("Result1",result1)
})
you can copy code and android will convert that code to kotlin.
I have a CheckBox written programmatically in android, it is programmatically written because the value of the CheckBox will be based on online content, so basically, the program has no idea on how many CheckBox will going to print. I use for loops to print checkboxes, and it was successful, but among those checkboxes, I want to get the value of the CheckBox that will going to be selected.
How can I do that?
String ans = _jsonObject.optString("choices").toString();
String[] ansar = ans.split("`");
cb = new CheckBox[ansar.length];
for (int z = 0; z<ansar.length; z++){
CheckBox cb = new CheckBox(survey);
cb.setText(ansar[z]);
choiceslayouts.addView(cb);
}
You need to create a boolean array for saving the state of all checkbox
Then add setOnCheckedChangeListener for each CheckBox
String ans = _jsonObject.optString("choices").toString();
String[] ansar = ans.split("`");
boolean[] array = new boolean[ansar.length];
for (int z = 0; z<ansar.length; z++){
...
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
array[z] = isCheck;
}
});
}
OR
You can set the tag for each CheckBox to check the state of CheckBox
1.Implement onClickListener for your Activity
public YourActivity extends Activity implements View.OnClickListener
2.Then set the tag for each CheckBox
for (int z = 0; z<ansar.length; z++){
...
cb.setTag("tag"+z);
cb.setOnClickListener(this);
}
3.Finnaly, implement onClick
public void onClick(View v) {
switch (v.getTag()) {
case "tag0":
if(((CheckBox) v).isChecked()) {
// your checkbox 0 is checked
}else{
// your checkbox 0 is not checked
}
break;
case "tag1":
// do the same
break;
...
}
}
Hope this help
I think you should use a ListView or a RecyclerView with custom layout and custom adapter, in order to optimize performance. Anyway it should be possible to achieve what you're look for without a major change to your code.
Your problem is that in the for loop you recreate a new checkbox with the exact same properties as the previous one, so even if you add it to your parent view, you are basically adding the same checkbox over and over again, and you can't listen to the event in the "single" checkboxes.
You should try something like this:
String ans = _jsonObject.optString("choices").toString();
String[] ansar = ans.split("`");
final boolean[] cbValue = new boolean[ansar.length];
cb = new CheckBox[ansar.length];
for (int z = 0; z<ansar.length; z++){
cb[z] = new CheckBox(survey);
cb[z].setText(ansar[z]);
cb[z].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cbValue[z] = !cbValue[z];
}
});
choiceslayouts.addView(cb[z]);
}
cbValue[] should hold the values of your checkboxes.
This is without error-checking, but it should give you the idea.
In my activity I have the following views
TextView player1;
TextView player2;
TextView player3;
TextView player4;
EditText player1name;
EditText player2name;
EditText player3name;
EditText player4name;
Each of the TextView's has the onclick listener applied to it. and so fires the OnClick function.
When we get to the onClick this is what i am currently doing:
#Override
public void onClick(View v) {
//the v variable is the clicked textview, in this case "player1"
//hide the textview and show the resultant edittext
v.setVisibility(View.GONE);
player1name.setVisibility(View.VISIBLE);
//set focus on edit text and when focus is lost hide it and set the textview text
player1name.requestFocus();
imm.showSoftInput(player1name, InputMethodManager.SHOW_FORCED);
player1name.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View y, boolean x) {
v.setVisibility(View.VISIBLE);
player1name.setVisibility(View.GONE);
imm.hideSoftInputFromWindow(player1name.getWindowToken(), 0);
String name = player1name.getText().toString();
if (name.equals("")) {
v.setText("Player Name1");
} else {
v.setText(name);
}
}
});
}
However with this solution I will need to duplicate this code and change the view names for player2 - player2name, player3 - player3name etc
i can obviously grab the clicked TextView via v, however what i cant seem to do is grab its corresponding EditText.
i had thought of doing this:
View test = v + "name";
//then i replace all references to player1name with the test variable
but it doesnt work it wants me to convert View test; into a string
any suggestions?
EDIT: made it easier to understand my question
View test = v + "name";
will give a compile error. Because "v" is not a string type. and also even if it was String, test is not. This line is pretty wrong.
There a few options to achieve what you want,
You can use hashmap
Declare a global field for hashmap
private final HashMap<Integer,EditText> map = new HashMap<Integer,EditText>();
and in onCreate method put your textview id as key, and put your edittext variables in value.
player1name = (EditText) findViewById(R.id.player1name);
map.put(R.id.textView1, player1name);
// for the rest
in onClick method
EditText e = map.get(v.getId());
Then replace them with "e"
e.requestFocus(); //example
Will you please state your problem clearly? Currently, your language is very ambiguous and I can not figure out, exactly what are you looking for. It will help us to know your problem and in turn solve it.
I want to grab Text when user click on the TextView
For Example :
TextView string = "this is a test for android and textView"
When user click on textview in android position grab android
Anyone have a solution for this ?
You can assign an onClick listener to the textview, make it final and then get its text.
final TextView txt = (TextView) findViewById(R.id.txt);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String getTxt = txt.getText().toString();
}
});
TextView text = (TextView) findViewById(R.id.yourTextViewId);
text.onClickListner(this);
#Override
public void onClick() {
String textOnTextView = text.getText().toString();
}
If you want to split lines and display them in different color then refer to following links.
Split text from string
Apply color to specific text
A button has onClick , I dont think that a TextView has onClick so that a user clicks it.
Correct me if i am wrong
If you want to select part of text, try to use EditText
This is not a solution for your need. But only one step to solution.
Use setTextIsSelectable(boolean) or the TextView_textIsSelectable XML attribute to make the TextView selectable (text is not selectable by default).
Using following code, I managed to get selected text as String. You need to first select string by dragging over it.
NB: you need minimum API 11 to use setTextIsSelectable(boolean)
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView) findViewById(R.id.textView1);
t1.setTextIsSelectable(true);// IMPORTANT
t1.setText("This is Android program");
t1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_UP:
int start=t1.getSelectionStart();
int end=t1.getSelectionEnd();
String sub=t1.getText().subSequence(start, end).toString();
Toast.makeText(getBaseContext(), sub, 1).show();
}
return true;
}
});
}
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;
}