Edit Text

The EditText control is a subclass of TextView. As suggested by the name, the EditText control allows for text editing. EditText is not as powerful as the text-editing controls that you find in JFC, for example, but users of Android-based devices probably won't type documents—they'll type a couple paragraphs at most. Therefore, the class has limited but appropriate functionality. For example, you can set the autoText property to have the control correct common misspellings. You can use the capitalize property to have the control capitalize words, the beginning of sentences, and so on. You can set the phoneNumber property if you need to accept a phone number. You can also set the password property if you need a password field.

The default behavior of the EditText control is to display text on one line and expand as needed. In other words, if the user types past the first line, another line will appear, and so on. You can, however, force the user to a single line by setting the singleLine property to true. In this case, the user will have to continue typing on the same line.

Software programming for mobile devices is all about helping the user make a decision quickly. Thus, a common task is to highlight or style a portion of the EditText's content. You can do this statically or dynamically. Statically, you can apply markup directly to the strings in your string resources (<string name="styledText"><i>Static</i> style in an <b>EditText</b>. </string>) and then reference it in your XML or from code. Note that you can use only the following HTML tags with string resources: <i>, <b>, and <u>.

Styling an EditText control's content programmatically requires a little additional work but allows for much more flexibility (see Listing 4-6).

Listing 4-6. Applying Styles to the Content of an EditText Dynamically

EditText et =(EditText)this.findViewById(R.id.cctvex5); et.setText("Styling the content of an editText dynamically"); Spannable spn = et.getText();

spn.setSpan(new BackgroundColorSpan(Color.RED), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

spn.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC) , 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

As shown in Listing 4-6, you can get the content of the EditText (as a Spannable object) and then set styles to portions of the text. The code in the listing sets the text styling to bold and italics and sets the background to red. Of course, you are not limited to bold, italics, and underline as before.

+2 0

Post a comment