Showing posts with label EditText. Show all posts
Showing posts with label EditText. Show all posts

11 October 2014

AutoCompleteTextView Hell

Today, I ran into a weird "feature" of Android. I was working on an AutoCompleteTextView with the dropdown list having section dividers. It all works well in portrait mode, but gets all messed up in landscape.

I made a sample app to illustrate the point of this blog [Github repo]. Clone it, run it, rotate the phone, select an item from the suggested auto-complete results, and get your mind blown. Or your heart stabbed. Or your stomach sucker-punched. Your choice.

So what was happening? Here's what.

When we tell the app to perform a filter, we construct an array of the resulting matches. The example is pretty straightforward, just look for countries that start with whatever the user has typed in.

// Filter by start of string
String country = mCountries.get(i);
if(country.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
    mFilteredData.add(country);
}
You can make this filtering as complicated as you like or need, just make sure to pass in whatever the user needs to see.

To illustrate having section headers (aka disabled items), we insert dummy text every fifth place in the list. The sample app does not care if there are more results after a section header, we still insert anyway.

So. Let's filter. Typing in "pa" will give us this set of data:
10-11 02:45:46.028  16282-20011/com.blogspot.droidista.autocompletetextviewhell D/AutoCompleteFragment﹕ 
Filtered results: [Section!, Pakistan, Palestine, Panama, Papua New Guinea, Section!, Paraguay]

There are two sections and five countries. Remember this.
Position in listValue
0Section!
1Pakistan
2Palestine
3Panama
4Papua New Guinea
5Section!
6Paraguay

This screenshot shows how the results are rendered in portrait mode. So far, so good. Selecting an item from the list populates the EditText with the country's name.

Now let's try rotating our phone. This is where things get juicy. First off, there are no section headers. Second, the results are not in alphabetical order anymore. If we debug all over the adapter, we see what is written on the screenshot: Item on the left is position = 1, item in the middle is position = 0, and item on the right is position = 2.

Remember the result set we have? "Pakistan" is definitely NOT in position = 0, it should have been a section header! If we go ahead and select "Pakistan" in the suggestions above the keyboard, the EditText will populate with the item in position = 0 of the result set, i.e. "Section!". Definitely not good.


The AutoCompleteTextView widget has been around since API level 1, but I haven't messed around with it as much as I did today. Googling returns very, very sparse results on this topic.
  • Does this mean people do not have the same problem as I did?
  • No one uses section headers in AutoCompleteTextViews?
  • No one uses this screen mode (EditText in full screen) in landscape without setting IME flags?
  • Is there a secret trick to making this work out-of-the-box?
Or the most plausible of all,
  • Am I being stupid?

05 June 2014

Adding attributes to a custom view

There are times when using the default Android Views just doesn't cut it and you need to create your own version of a View. So how exactly do you do that? It's as simple as subclassing the View! But what if you want to add customizable attributes? Here's how.

Let's say I am creating a form-filling application and I want some of the EditTexts in the form to be required. However, I am so tired of having to implement the error checking for each and every one of those fields. What I will do is create my own EditText that will do the validation for me if that particular field is required. Let's do it.

Step 1: Create your custom view and create fields for the attributes you want. In this case, I want an EditText that will show the default EditText error display if the user has not put in any value.
public class RequiredEditText extends EditText {
   private boolean mRequired;
   private String mErrorMessage;

   public RequiredEditText(Context context) {
      super(context);
   }

   /**
   * Set this EditText's requirement validation. The error message
   * will be set to null by default if not provided.
   * 
   * @param required
   * @param errorMessage (optional)
   */
   public void setRequired(boolean required, String errorMessage) {
      this.mRequired = required;
      this.mErrorMessage = errorMessage;
  
      invalidate();
      requestLayout();
   }
 
   public void setRequired(boolean required) {
      setRequired(required, null);
   }

   /**
   * Lets you know if this field is set as required or not
   * @return
   */
   public boolean isRequiredField() {
   return mRequired;
   }
}
Step 2: If a field is required, we want the default error message to appear (with our own error message, of course). If the user fills in the EditText, we want the error to disappear.
public class RequiredEditText extends EditText {
   private boolean mRequired;
   private String mErrorMessage;

   public RequiredEditText(Context context) {
      super(context);
   }

   /**
   * Set this EditText's requirement validation. The error message
   * will be set to null by default if not provided.
   * 
   * @param required
   * @param errorMessage (optional)
   */
   public void setRequired(boolean required, String errorMessage) {
      this.mRequired = required;
      this.mErrorMessage = errorMessage;
  
      manageRequiredField(required);
  
      invalidate();
      requestLayout();
   }
 
   public void setRequired(boolean required) {
      setRequired(required, null);
   }

   private void manageRequiredField(boolean required) {
      // If we are required, set the listeners
      if(required) {
         setOnFocusChangeListener(mFocusChangeListener);
         addTextChangedListener(mTextWatcher);
      } else {
         // In case there is an error message already, clear it
         setError(null);
   
         // Remove the listeners
         setOnFocusChangeListener(null);
         removeTextChangedListener(mTextWatcher);
      }
   }

   /**
   * Lets you know if this field is set as required or not
   * @return
   */
   public boolean isRequiredField() {
      return mRequired;
   }

   OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {

      @Override
      public void onFocusChange(View v, boolean hasFocus) {
         // If the focus was removed from the field and it IS required,
         // check if the user has put in something
         if(!hasFocus && mRequired){
            isRequiredFieldFilled();
         }
      }
   };
 
   TextWatcher mTextWatcher = new TextWatcher() {

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
         // Once the user types in something, remove the error
         setError(null);
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* do nothing */ }

      @Override
      public void afterTextChanged(Editable s) { /* do nothing */ }   
   };

   private boolean isRequiredFieldFilled() {
      // If the EditText is empty, show the error message
      if(TextUtils.isEmpty(getText().toString().trim())){
         showRequiredErrorDrawable();
         return false;
      }
      return true;
   }

   private void showRequiredErrorDrawable() {
      setError(mErrorMessage);
   }
}
Step 3: Now it's time to add the fields to the Layout Editor. Create an attrs.xml file in /res if there isn't one already. Declare a styleable and include the attributes you want to appear in the Layout Editor.

   
       
       
   

The name of the styleable does not need to match your custom view class name, but doing so makes it more readable and maintainable.

Step 4: Go back to your custom view implementation and add constructors that take in an AttributeSet.
public RequiredEditText(Context context, AttributeSet attrs, int defStyle) {
   super(context, attrs, defStyle);
   init(attrs);
}

public RequiredEditText(Context context, AttributeSet attrs) {
   super(context, attrs);
   init(attrs);
}

private void init(AttributeSet attrs) { 
   TypedArray a=getContext().obtainStyledAttributes(
      attrs,
      R.styleable.RequiredEditText);

   try {
      setRequired(a.getBoolean(R.styleable.RequiredEditText_required, false), 
            a.getString(R.styleable.RequiredEditText_errorMessage));
   } finally {
      //Don't forget this, we need to recycle
      a.recycle();
   }
}
Step 5: Go to the Layout Editor and look for "Custom & Library Views" in the Palette (you may have to click on "Refresh" several times before your custom view appears in the list). Add the custom view to your layout and check out the properties panel!
 

 As always, the code is in GitHub.

31 March 2011

My EditText is cut off by the on-screen keyboard!

With clients demanding left and right that my app should look like an iPhone app, I tend to be unappreciative of the way Android natively handles UI interactions and such. Notice how the screen automagically scrolls up when you click on an EditText? It turns out that in iPhone development, the developer does this manually (indicate how much the view should scroll when the on-screen keyboard appears, then scroll it back down afterwards). HA!

But even magic fails sometimes. Has this ever happened to you?

The bottommost EditText is cut off. And we don't want that!

So what do we do? Do we programmatically scroll the view up? I don't want to do that! It turns out that we can just wrap the whole view in a ScrollView and it will scroll up properly!


The only downside to this is that you might want to hide the scrollbar when the view moves up to accommodate the on-screen keyboard. And to do that, I was trying to set the android:scrollbars="none" attribute but for one reason or another the scrollbar is still being drawn. To make the scrollbar disappear, we can do it from code as such:
((ScrollView)findViewById(R.id.my_scrollview))
.setVerticalScrollBarEnabled(false);
And we're done!