I have a number picker set up with strings but I am having a problem with getting the string that is being displayed.
Here is the code for the construction of the number picker.
fractionPicker is my Number picker .
void fractionPickerFunction(){
final String[] arrayString= new String[]{"None", "1/8", "1/4", "3/8", "1/2", "5/8", "3/4", "7/8"};
fractionPicker.setMinValue(0);
fractionPicker.setMaxValue(arrayString.length-1);
fractionPicker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int value) {
return arrayString[value];
}
});
}
Set a change listener if you need to just get the result. If you need to modify the variable with the setFormatter still then just use both. call your setFormatter, then also add the change listener. It will then return to you, your modified variable.
Change
void fractionPickerFunction(){
final String[] arrayString= new String[]{"None", "1/8", "1/4", "3/8", "1/2", "5/8", "3/4", "7/8"};
fractionPicker.setMinValue(0);
fractionPicker.setMaxValue(arrayString.length-1);
fractionPicker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int value) {
return arrayString[value];
}
});
}
To this:
fractionPicker.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// TODO Auto-generated method stub
String Old = "Old Value : ";
String New = "New Value : ";
}
});
You should refer to the android documentation on the NumberPicker. In short,
you are going to want to set a OnValueChangeListener by calling setOnValueChangedListener on your NumberPicker. You can do that with the following:
fractionPicker.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// Do your work here
// Parameters
// picker NumberPicker: The NumberPicker associated with this listener.
// oldVal int: The previous value.
// newVal int: The new value.
}
});
Related
I'm desperately trying to simulate a click on a spinner item with Espresso.
The spinner is populated with objects from the class Project. This class has a toString() method, which allows the spinner to display String.
private void populateDialogSpinner() {
final ArrayAdapter<Project> adapter2 = new ArrayAdapter<Project>(this, android.R.layout.simple_spinner_item, allProjects);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vm.getAllProjects().observe(this, projects -> {
allProjects.clear();
allProjects.addAll(projects);
adapter2.notifyDataSetChanged();
});
I have found several solutions in order to use this spinner with Espresso but none of them has worked. This is my Test class.
#Test
public void addActivity () throws InterruptedException {
onView(withId(R.id.fab_add_task)).perform(click());
onView(withId(R.id.txt_task_name)).perform(replaceText(textTaskText), closeSoftKeyboard());
onView(withId(R.id.project_spinner)).perform(click());
// A few solutions I have tried :
// 1 onView(withText("Projet Lucidia")).perform(click());
// 2 onData(anything())
// .inAdapterView(withId(R.id.project_spinner))
// .onChildView(withMyValue("Projet L"))
// .perform(click());
// 3 onData(anything()).atPosition(1).perform(click());
// 4 onView(allOf(withId(R.id.project_spinner), withSpinnerText("Project Lucidia"))).perform(click());
withMyValue refers to this class
public static Matcher<View> childAtPosition(final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
#Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
#Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent) && view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
Each time, the emulator stays with the spinner open like this :
Any idea of how I can handle this?
I'm not sure if it's the best answer but I have found this code thats works perfectly well.
UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiObject spinnerItem = uiDevice.findObject(new UiSelector().text("Projet Lucidia"));
spinnerItem.click();
I am trying to convert a value that has been passed through from another fragment. The convert method is inside an onClickListener which when clicked will make the conversion of the value passed through the fragment.
The values are currently being placed into TextViews on my second fragment. However when I try to make an if statement it won't enter the loop
Text Name is what my textView has been set to.
The code is here
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textName.equals("Miles") && textName2.equals("Kilometers")) {
String str1 = editText1.getText().toString();
double unittoConvert = Double.parseDouble(str1);
double convertedUnit = unittoConvert * 1.6;
String result = Double.toString(convertedUnit);
textName3.setText(result);
}
}
});
This is the code for the methods that are setting the unit selected in scroller and passing it through to the text view which is then displaying the selected unit. When i try to extract these values it wont work
PageViewModel.getName().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName.setText(s);
}
});
PageViewModel2.getName2().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName2.setText(s);
}
});
Use getText to extract text from TextView and then compare
textName.getText().equals("Miles") && textName2.getText().equals("Kilometers")
I am making android app and I have edit text surrounded by two buttons for increase and decrease
and when I click the button increase or decrease for the first time it did not work but it start working from the second time
e.g if the number in edit text field is 50 when I press increase it still 50 when I press increase again it change to 51 and again it change to 52 and so on
here is my java code for the two buttons
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (quantityEdit.getText().toString().equals("") || quantityEdit.getText().toString() == null) {
quantityEdit.setText("0");
} else {
int a = Integer.parseInt(quantityEdit.getText().toString());
int b = a + 1;
quantityEdit.setText(String.valueOf(b));
}
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int a = Integer.parseInt(quantityEdit.getText().toString());
if (a >= 1) {
int b = a - 1;
quantityEdit.setText(String.valueOf(b));
} else {
quantityEdit.setText("0");
}
}
});
It looks like you are checking for empty string or null in "add", but not in "sub". As Michael Krause said, you should use TextUtils.isEmpty(), and set a default value before performing add or sub operations.
If you are setting a default value elsewhere, please show your code.
Consider refactoring your code like so
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quantityEdit.setText(String.valueOf(getIntVal(quantityEdit) + 1));
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int value = getIntVal(quantityEdit);
if (value > 0) {
value--;
}
quantityEdit.setText(String.valueOf(value));
}
});
// helper method to get the integer value of a TextView
private int getIntVal(TextView textView) {
CharSequence rawValue = textView.getText();
int value;
if (!TextUtils.isEmpty(rawValue)) {
try {
value = Integer.parseInt(rawValue.toString());
} catch (NumberFormatException e) {
value = 0;
// TODO log / notify user
}
} else {
value = 0;
}
}
This way your initialization is handled in one place and it's more clear.
In any event, your first condition is wrong. You do a null check after trying to access the object (it's backwards). Have you checked your logs? This could throw an exception for a null value and "lose" the first click.
I'm making a small app on android studio and I have different EditText fields that I want to change the background to 3 colors depending on the value inside. 1 for if value is equal to goal and 1 for less than goal and last one for more (<,=,>). I already set up colors in the style category but I have no idea how to make the code on the main.java so that it recognizes the EditText fields and change the color according to the value given when compared to the goal.
Text Watcher
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
However you want to use this. You can do it as the user is type in their message, or if they click a button, etc.
To use it, you can do something like this... (in side the method)
if(s.equals("1")){
editText.setBackgroundResource(getResources().getColor(R.color.blue));
}
First, use findViewById to get a reference to the EditText field you want to compare, and assign it to a variable:
EditText enteredValueEditText = findViewById(R.id.entered_value_edittext);
Next, retrieve the value from the EditText field:
String value = enteredValueEditText.getText().toString().trim();
Convert to an integer:
int valueInt = Integer.parseInt(value);
Then, compare it to your goal value and set the background color appropriately using the setBackgroundColor command:
if (goal > valueInt) {
enteredValue.setBackgroundColor(getResources().getColor(R.color.green));
} else if (goal < valueInt) {
enteredValue.setBackgroundColor(getResources().getColor(R.color.red));
} else if (goal == valueInt) {
enteredValue.setBackgroundColor(getResources().getColor(R.color.blue));
}
This is my edittext
<EditText
android:id="#+id/etWaardeVan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:digits="0123456789."
android:inputType="number|numberDecimal"
android:scrollHorizontally="true"
android:singleLine="true"
/>
How do I programmatically allow for only one dot to be input.
Is this what you are looking for?
Set EditText Digits Programmatically
etWarDevan.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
I'd remove the last entered character if its a dot and there has been one before.
EditText field = view.findViewById(R.id.etWaardeVan);
field.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable editable) {
String str = editable.toString();
String strold = str.substring(0, str.length() - 2);
String lastchar = str.substring(str.length() - 1);
if(strold.contains(".") && lastchar.equals(".")) field.setText(str);
}
});
Hint: this only works if the user doesn't jump back and enters the dot in the middle of the string. You may want to disable cursor movement. (Like this or using android:cursorVisible)
Alternatively (if the input always contains a dot) you can just create two EditTexts without a dot allowed.
Here is my solution, and it works:
dot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//only show one dot if user put more than one dot
if(input.contains(".")){
//then save what it has
input = textView.getText().toString();
}else {
//concat the input value
input=input+".";
}
}
});
Basically, EditText is derived from TextView which has a
void addTextChangedListener(TextWatcher watcher)
method. TextWatcher has callbacks, like
abstract void afterTextChanged(Editable s)
that you can implement in order to filter the new text to only contain period.
Regex: (?<=^| )\d+(\.\d+)?(?=$| )
Example
et1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// Do something here with regex pattern
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
In AfterTextChangeListener add Regex
val isSingleDot = Regex("\.").findAll("sample.sample").count() <= 1
Set inputType attribute in EditText/TextInputEditText as android:inputType="numberDecimal"