Seekbars and EditTexts - android

I am working on an application in which I need the user to set an array of 30 values and to make it user friendly and easy to use I have decided to use a series of SeekBars and EditText widgets. I am using eclipse and have used it to set up the layout.
I am looking for an efficient way to set up the application to automatically update the value of the SeekBar when the value of the EditText has been changed and then use that same value in a application integer array.
<SeekBar android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:max="255"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:padding="10dp"
android:id="#+id/seekX"></SeekBar>
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".01"
android:minWidth="50sp"
android:maxWidth="50sp"
android:gravity="center_horizontal"
android:padding="10dp"
android:layout_marginRight="10dp"
android:inputType="number"
android:id="#+id/editX"></EditText>
The seek bars and EditText fields are named in a corresponding way editX should match seekX as editY should match seekY and so on. I am also storing the values in the int[] upgradeValues.
I have also set the SeekBar to have a max of 255 but i need a way to automatically change any value set in the EditText field above 255 down to 255 and similarly any value below 0 to 0.
Basically I need an efficient way of making "(ValueOF)seekX = (ValueOf)editX = (ValueOf)upgradeValues[x] >= 0 <= 255" and be updated if seekX or editX is changed.

I am still pretty new to Android development, so this answer isn't very specific, but hopefully it gets you on your way.
There are a few approaches. You can set change listeners on both of your seekbar and the edittext that update the values of the other (suppose you have your EditText t, SeekBar b and the value in model:
b.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(final SeekBar seekBar,
final int progress,
final boolean fromUser)
{
if (fromUser)
{
model = progress;
updateUI();
}
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(final SeekBar seekBar)
{
}
});
t.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(final View v,
final int keyCode,
final KeyEvent event)
{
model = Integer.parseInt(t.getText().toString());
updateUI();
return true;
}
});
Then updateUI() would be something like:
private void updateUI()
{
t.setText(model);
b.setProgress(model);
}
Those are some crazy names and I clearly did no error checking. But you get the idea. This is probably NOT the way you want to go, because you have to make sure you catch all the different ways the user interacts with each component (onKey probably isn't enough to detect whenever the EditText value changes).
The proper (MVC) way is to have your model (your int[]) contain the value and have your SeekBar and EditText use your model as their models. I don't know how to do that in Android's UI model.

Related

Android sliders with fixed numbers

I'm trying to implement a discrete slider with fixed values, but the only thing I can set is the valueFrom, valueTo and stepSize.
Here is my code how I'm trying to do
<com.google.android.material.slider.Slider
android:id="#+id/slider"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="8dp"
app:tickColor="#color/colorSecondaryLight"
app:tickColorActive="#color/colorSecondary" />
Is there a way to set fixed values on the slider? (Values that I will use 2, 5, 10, 25, 50 and 100)
The solution that worked for me was this lib called BubbleSeekBar
Step 1 - Add the dependencies on your Gradle.
implementation "com.xw.repo:bubbleseekbar:3.20-lite"
Step 2 - Create your BubbleSeekBar on your XML and add the attributes that you need. For my case, the example below worked.
<com.xw.repo.BubbleSeekBar
android:id="#+id/bubbleSeekBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:bsb_auto_adjust_section_mark="true"
app:bsb_hide_bubble="true"
app:bsb_min="2"
app:bsb_section_count="5"
app:bsb_section_text_position="below_section_mark"
app:bsb_seek_by_section="true" />
Step 3 - Since I needed custom options, I initialized on my onCreate with the array of values declared on my string.xml
bubbleSeekBar.setCustomSectionTextArray { sectionCount, array ->
array.clear()
for ((index, value) in resources.getStringArray(R.array.xxxx)
.withIndex()) {
array.put(index, value)
}
array
}
Step 4 - You can capture the changes or set a value with the methods below.
bubbleSeekBar.onProgressChangedListener
bubbleSeekBar.setProgress()
The lib is pretty good and worked for me. For more info take a look at the link at the top of this answer.
You'd be better off using SeekBar
<SeekBar
android:id="#+id/sb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:thumb="#drawable/ic_location"
android:theme="#style/Widget.AppCompat.SeekBar.Discrete" />
You can use a SeekBar and define the range of values, and in order to remove the smoothness/refining scrolling, set OnSeekBarChangeListener to it and override onProgressChanged() with the valid range of the SeekBar values you need by setting the progress again as below.
Example
Using a SeekBar with a max value of 100, and a step of 10; so the total valid values are 10.
SeekBar seekBar = findViewById(R.id.seekbar);
seekBar.setMax(100);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean
fromUser) {
seekBar.setProgress((progress / 10) * 10);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});

Text Watcher Binding Adapter with ViewModel

I'm still new to all this MVVM and Android Architecture Components. I have a few screens (Login and Register) that have inputs for email, password, name etc and a 'continue' button that's only enabled when the required fields are filled out correctly. There's also text views for messages such as "password must be..." and "not a valid email...". I'm trying to use a binding adapter and viewmodel to pull some of this validation logic out of my MainActivity and away from my business logic, but I'm struggling. I'm not even sure if this is the best way to do it. My thought with the ViewModel is that it would hold it's state on rotation/activity changes.
RegisterActivity is an Activity that simply holds a ViewPager with 3 fragments (email/password, first/last name, validation code).
Binding Adapter
#BindingAdapter("app:onTextChanged")
public static void onTextChanged(TextInputEditText view, TextViewBindingAdapter.OnTextChanged listener) {
}
Layout
<TextView
android:id="#+id/tv_error_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/register_email_requirement"
android:textColor="#color/moenPrimaryError"
android:textSize="18sp"
android:visibility="#{viewModel.emailValidationVisible ? View.VISIBLE: View.GONE}"
app:layout_constraintBottom_toTopOf="#id/input_layout_password"
app:layout_constraintEnd_toEndOf="#+id/input_layout_email_address"
app:layout_constraintStart_toStartOf="#+id/input_layout_email_address"
app:layout_constraintTop_toBottomOf="#+id/input_layout_email_address"
app:layout_goneMarginTop="16dp" />
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/input_email_address"
style="#style/MoenTextInputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
app:onTextChanged="#{viewModel.onTextChanged}"
app:onFocusChange="#{inputLayoutEmailAddress}">
</com.google.android.material.textfield.TextInputEditText>
ViewModel
public class RegisterFragmentViewModel extends BaseObservable {
private boolean emailValidationVisible = false;
#Bindable
public boolean getEmailValidationVisible() {
return this.emailValidationVisible;
}
public void toggle() {
this.emailValidationVisible = !this.emailValidationVisible;
notifyPropertyChanged(BR.viewModel);
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.w("tag", "onTextChanged " + s);
this.toggle();
}
}
This is just a test I have. My thought was that I could bind the TextView visibility to a boolean that I can toggle/manipulate with a onTextChanged listener, but I don't know how to wire up the Binding Adapter. Am I on the right path? Is there a better/easier way to do this?
Am I on the right path? Is there a better/easier way to do this?
it is a way of doing it. I would remove the ternary operator from this line
android:visibility="#{viewModel.emailValidationVisible ? View.VISIBLE: View.GONE}"
and create a simple function in your VM that returns it. EG:
#Bindable
public int getVisibility() {
return emailValidationVisible ? View.VISIBLE: View.GONE
}
and in toggle(), you will have something like
public void toggle() {
this.emailValidationVisible = !this.emailValidationVisible;
notifyPropertyChanged(BR.visibility);
}
which will call the getter for you. Your xml will have to be changed like follow
android:visibility="#{viewModel.getVisibility()}"
Alternately you could create a BindingAdapter that takes a Boolean and change the visibility accordingly to it

SeekBar: ProgressDrawable does only show after first progress Change

I want to implement a easy hsv color picker that fit well into my app. As known form color Pickers I would like to change the background of the seekBars according to the value of the other seekBars.
But when I start the activity I am seeing this:
After the first touch of one of the seekBars (no matter which) I get this result and after the first touch the layout stays like this and does not change with further touches (which is also what I would have expected according to my layout, the 2 seekBars on top are 20dip and the 1 below is as high as the thumb):
Like seen in the second picture I would like to have the seekBar from beginning.
Here my layout:
<SeekBar
android:id="#+id/SbColorPickerHue"
android:layout_width="match_parent"
android:layout_height="20dip"
android:max="360"
android:thumb="#drawable/colorpickerthumb" />
<SeekBar
android:id="#+id/SbColorPickerSaturation"
android:layout_width="match_parent"
android:layout_height="20dip"
android:max="255"
android:thumb="#drawable/colorpickerthumb"/>
<SeekBar
android:id="#+id/SbColorPickerValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="255"
android:thumb="#drawable/colorpickerthumb"/>
With a OnSeekBarChangeListener in onProgressChanged() and of course in onCreate (to initalize the seekBars) I am calling the following function (To safe you a lot of code only the Hue Gradient is shown):
private void setGradients() {
mHueGradient = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,mColors);
mHueGradient.setGradientType(GradientDrawable.LINEAR_GRADIENT);
mHueGradient.setCornerRadius(mRadius);
mHueGradient.setStroke(mStrokeWidth, mStrokeColor);
mSbHue.setBackgroundDrawable(mHueGradient);
}
I tried many different things already:
set the Gradients twice in onCreate
set the Gradients again in onRescume
as can be seen in the layout xml I set some of the SeekBar to a fixed height (20dp) and others to wrap_content. The behaviour changed a little (as can be seen in the pictures). But still not satisfying.
Invalidate either the seekBar or the Drawable
Force Layout
Measure the drawable
Result is always the same.
What am I doing wrong here? Am I missing somthing?
Edit 1:
The SeekBar and the ChangeListener are defined as follows:
mSbHue = (SeekBar)findViewById(R.id.SbColorPickerHue);
setGradients();
mSbHue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
setGradients();
}
});
If you move setGradients() after the listener it works.
mSbHue = (SeekBar)findViewById(R.id.SbColorPickerHue);
mSbHue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
setGradients();
}
});
setGradients();

Make EditText ReadOnly

I want to make a read-only EditText view. The XML to do this code seems to be android:editable="false", but I want to do this in code.
How can I do this?
Please use this code..
Edittext.setEnabled(false);
If you setEnabled(false) then your editText would look disabled (gray, etc). You may not want to change the visual aspect of your editor.
A less intrusive way would be to use setFocusable(false).
I believe that this answers your question closer to your initial intent.
In XML use:
android:editable="false"
As an example:
<EditText
android:id="#+id/EditText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false" />
This works for me:
EditText.setKeyListener(null);
editText.setInputType(InputType.TYPE_NULL);
As per the docs this prevents the soft keyboard from being displayed. It also prevents pasting, allows scrolling and doesn't alter the visual aspect of the view. However, this also prevents selecting and copying of the text within the view.
From my tests setting setInputType to TYPE_NULL seems to be functionally equivalent to the depreciated android:editable="false". Additionally, android:inputType="none" seems to have no noticeable effect.
android:editable="false" has been deprecated. Therefore you cant use it to make the edit text readonly.
I have done this using the bellow solution. Here I have used
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
Give it try :)
<EditText
android:id="#+id/et_newsgpa_university"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/hint_educational_institute"
android:textSize="#dimen/regular_text"
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
android:maxLines="1"
android:imeOptions="actionNext"/>
The best is by using TextView instead.
editText.setEnabled(false);
editText.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
} });
This will give you uneditable EditText filter. you first need to put the text you want on the editText field and then apply this filter.
writing this two line is more than enough for your work.
yourEditText.setKeyListener(null);
yourEditText.setEnabled(false);
set in XML
android:inputType="none"
Try using
editText.setEnabled(false);
editText.setClickable(false);
Try overriding the onLongClick listener of the edit text to remove context menu:
EditText myTextField = (EditText)findViewById(R.id.my_edit_text_id);
myTextField.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
android:editable
If set, specifies that this TextView has an input method. It will be a textual one unless it has otherwise been specified. For TextView, this is false by default. For EditText, it is true by default.
Must be a boolean value, either true or false.
This may also be a reference to a resource (in the form #[package:]type:name) or theme attribute (in the form ?[package:][type:]name) containing a value of this type.
This corresponds to the global attribute resource symbol editable.
Related Methods
If you just want to be able to copy text from the control but not be able to edit it you might want to use a TextView instead and set text is selectable.
code:
myTextView.setTextIsSelectable(true);
myTextView.setFocusable(true);
myTextView.setFocusableInTouchMode(true);
// myTextView.setSelectAllOnFocus(true);
xml:
<TextView
android:textIsSelectable="true"
android:focusable="true"
android:focusableInTouchMode="true"
...
/>
<!--android:selectAllOnFocus="true"-->
The documentation of setTextIsSelectable says:
When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value...
However I had to explicitly set focusable and focusableInTouchMode to true to make it work with touch input.
Use this code:
editText.setEnabled(false);
editText.setTextColor(ContextCompat.getColor(context, R.color.black);
Disabling editText gives a read-only look and behavior but also changes the text-color to gray so setting its text color is needed.
this is my implementation (a little long, but useful to me!):
With this code you can make EditView Read-only or Normal. even in read-only state, the text can be copied by user. you can change the backgroud to make it look different from a normal EditText.
public static TextWatcher setReadOnly(final EditText edt, final boolean readOnlyState, TextWatcher remove) {
edt.setCursorVisible(!readOnlyState);
TextWatcher tw = null;
final String text = edt.getText().toString();
if (readOnlyState) {
tw = new TextWatcher();
#Override
public void afterTextChanged(Editable s) {
}
#Override
//saving the text before change
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
// and replace it with content if it is about to change
public void onTextChanged(CharSequence s, int start,int before, int count) {
edt.removeTextChangedListener(this);
edt.setText(text);
edt.addTextChangedListener(this);
}
};
edt.addTextChangedListener(tw);
return tw;
} else {
edt.removeTextChangedListener(remove);
return remove;
}
}
the benefit of this code is that, the EditText is displayed as normal EditText but the content is not changeable. The return value should be kept as a variable to one be able revert back from read-only state to normal.
to make an EditText read-only, just put it as:
TextWatcher tw = setReadOnly(editText, true, null);
and to make it normal use tw from previous statement:
setReadOnly(editText, false, tw);
This worked for me, taking several of the suggestions above into account. Makes the TextEdit focusable, but if user clicks or focuses, we show a list of selections in a PopupWindow. (We are replacing the wacky Spinner widget). TextEdit xml is very generic...
public void onCreate(Bundle savedInstanceState) {
....
fEditState = (EditText) findViewById(R.id.state_edit);
fEditState.setLongClickable(false);
fEditState.setKeyListener(null);
fEditState.setFocusable(true);
fEditState.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus)
{
showStatesPopup();
}
}
});
fEditState.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0)
{
showStatesPopup();
}
});
....
}
private void showStatesPopup()
{
// fPopupWindowStates instantiated in OnCreate()
if (!fPopupWindowStates.isShowing()) {
// show the list view as dropdown
fPopupWindowStates.showAsDropDown(fEditState, -5, 0);
}
}
This was the only full simple solution for me.
editText.setEnabled(false); // Prevents data entry
editText.setFocusable(false); // Prevents being able to tab to it from keyboard
As android:editable="" is deprecated,
Setting
android:clickable="false"
android:focusable="false"
android:inputType="none"
android:cursorVisible="false"
will make it "read-only". However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:
myEditText.setOnLongClickListener { true }
suffices.
My approach to this has been creating a custom TextWatcher class as follows:
class ReadOnlyTextWatcher implements TextWatcher {
private final EditText textEdit;
private String originalText;
private boolean mustUndo = true;
public ReadOnlyTextWatcher(EditText textEdit) {
this.textEdit = textEdit;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mustUndo) {
originalText = charSequence.toString();
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (mustUndo) {
mustUndo = false;
textEdit.setText(originalText);
} else {
mustUndo = true;
}
}
}
Then you just add that watcher to any field you want to be read only despite being enabled:
editText.addTextChangedListener(new ReadOnlyTextWatcher(editText));
I had no problem making EditTextPreference read-only, by using:
editTextPref.setSelectable(false);
This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html
private static final List<String> keyList;
static {
keyList = new ArrayList<String>();
keyList.add("field1");
keyList.add("field2");
keyList.add("field3");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
initSummary(getPreferenceScreen().getPreference(i));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
//editTextPref.setEnabled(false); // this can be used to 'gray out' as well
editTextPref.setSelectable(false);
if (keyList.contains(p.getKey())) {
p.setSummary(editTextPref.getText());
}
}
}
Set this in EdiTextView xml file
android:focusable="false"
in java file:
Edittext.setEnabled(false);
in xml file:
android:editable="false"
These 2 lines makes ur edittext selectable and at the same time not editable (it doesn't even show the soft keyboard):
editText.setInputType(InputType.TYPE_NULL);
editText.setTextIsSelectable(true);

hint and textview with right gravity and a singleline

I've opened a bug but i was wondering if anyone encountered this issue and knows a workaround.
If you define a text view with a hint inside it, give it right gravity (android:gravity="right") then if you define android:singleLine=true or android:maxLines="1" or android:scrollHorizonatally="true" you don't see the hint. removing the right gravity returns the hint to the left side, removing all the tree params i mentioned above puts the hint on the right side. i want my hint on the right, but i need a single horizontal line...
here's the sample layout that doesn't show the hint:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<EditText android:layout_width="fill_parent"
android:layout_gravity="center_vertical|right"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:textSize="16sp"
android:paddingRight="5dp"
android:id="#+id/c"
android:gravity="right"
android:hint="hello!!!"
android:scrollHorizontally="true"
android:maxLines="1"
android:singleLine="true"/>
</LinearLayout>
i checked on 1.6 and 2.1 emulators and it reproduces 100%, i'm prettysure it's a bug, i don't see the connection between single line and the hint.... what's more the hint got it's own layout in the TextView (mLayout and mHintLayout both exists, in onDraw if the text length is 0 mHintLayout if mHint is not null is used).
Did you try android:ellipsize="start"? This has worked great for me in the past when I've wanted my hint and EditText to be centered.
Looks like you're exactly right with the issue; I tried playing with your example layout and saw the same issue. I assume this is your bug report.
The easiest solution is to just change your layout, but that's probably not what you want to do. My first attempt at a work around would be to try not setting any of those three attributes in XML and then setting them in Java. If that doesn't work...
One option is to mimic the hint by either extending the EditText class and attempting to fix the code that lays out the hint yourself, or by overriding the onDraw method to create the hint, or perhaps by simply overlapping a regular TextView on top of the EditText, which you then show/hide manually. You could even have the view check if it's empty, and if so set the text to your hint text and change the color. When the view gains focus, check if its text is equal to your hint and, if so, remove the text and change the color back.
Another possible workaround that's a bit more "hacky" is to leave off the three attributes that cause problems, but try to manually prevent a newline from being created. You'd need to create an OnKeyListener for your EditText, something like this:
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
// do nothing
return true;
}
return false;
}
});
You would also want to call editText.setImeOptions(EditorInfo.IME_ACTION_NEXT) to avoid showing the return key. It still may be possible to create a newline in your text field by pasting into it or perhaps some other method, so you would also want to parse and remove newlines when the form is submitted just to be safe. This is also not likely to do what you want as far as horizontal scrolling.
use these properties with hint and single line...u can chnge gravity!!
android:gravity="right"
android:ellipsize="start"
android:imeOptions="actionNext"
android:singleLine="true"
Noting worked good enough for me. When I set Gravity.right, the cursor was always on the right and couldn't be placed in the middle of the word.
I tried a different approach - put the set the gravity the the right when there is no text (or left, if it works for you) and let android decide the best direction once the user entered something
This worked for me:
create TextWatcher class
private static class FilterTextWatcher implements TextWatcher {
private WeakReference<Activity> mActivity;
public FilterTextWatcher(Activity activity) {
mActivity = new WeakReference<Activity>(activity);
}
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (mActivity.get() == null)
return;
EditText searchTxtBx = mActivity.get().mSearchTxtBx;
if (searchTxtBx.getText().toString().length() == 0)
searchTxtBx.setGravity(Gravity.RIGHT);
else
searchTxtBx.setGravity(0);
}
}
use it as class member
private TextWatcher mFilterTextWatcher = new FilterTextWatcher(this);
in onCreate():
mSearchTxtBx.addTextChangedListener(mFilterTextWatcher);
in onDestroy():
mSearchTxtBx.removeTextChangedListener(mFilterTextWatcher);
mFilterTextWatcher = null;
What do you think about my solution to this problem?
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == false && StringUtils.isNotBlank(editText.getText().toString())) {
editText.setGravity(Gravity.RIGHT);
}
}
});
And the corresponding XML File:
<EditText android:id="#+id/the_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="number" android:hint="#string/edit_text_prompt"/>
Works fine for me: just one line, no enter-key possible, shows me the hint and when I leave the field after some input was given, the text appears right-aligned.
it worked with me when I added:
android:hint="the hint text ..."
android:singleLine="true"
android:ellipsize="start"
and in my activity i added :
myedittext.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_DOWN){
// do nothing
return true;
}
return false;
}
});
I noticed this issue when my TextView atrs are:
android:singleLine="true"
android:gravity="right"
When I try to Linkify the textview or setMovementMethod(LinkMovementMethod.getInstance()) on that textview, the text is just gone.
android:ellipsize="start"
solved my issue, because I use Arabic text in my app.

Categories

Resources