WebTextView.java revision 010582885cbd5e1becadd6c53816c399465b459d
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.webkit; 18 19import android.content.Context; 20import android.graphics.Canvas; 21import android.graphics.Color; 22import android.graphics.ColorFilter; 23import android.graphics.Paint; 24import android.graphics.PixelFormat; 25import android.graphics.Rect; 26import android.graphics.drawable.Drawable; 27import android.text.Editable; 28import android.text.InputFilter; 29import android.text.Selection; 30import android.text.Spannable; 31import android.text.TextPaint; 32import android.text.TextUtils; 33import android.text.method.MovementMethod; 34import android.text.method.Touch; 35import android.util.Log; 36import android.view.Gravity; 37import android.view.KeyCharacterMap; 38import android.view.KeyEvent; 39import android.view.MotionEvent; 40import android.view.View; 41import android.view.ViewGroup; 42import android.view.inputmethod.EditorInfo; 43import android.view.inputmethod.InputMethodManager; 44import android.view.inputmethod.InputConnection; 45import android.widget.AbsoluteLayout.LayoutParams; 46import android.widget.ArrayAdapter; 47import android.widget.AutoCompleteTextView; 48import android.widget.TextView; 49 50import java.util.ArrayList; 51 52/** 53 * WebTextView is a specialized version of EditText used by WebView 54 * to overlay html textfields (and textareas) to use our standard 55 * text editing. 56 */ 57/* package */ class WebTextView extends AutoCompleteTextView { 58 59 static final String LOGTAG = "webtextview"; 60 61 private WebView mWebView; 62 private boolean mSingle; 63 private int mWidthSpec; 64 private int mHeightSpec; 65 private int mNodePointer; 66 // FIXME: This is a hack for blocking unmatched key ups, in particular 67 // on the enter key. The method for blocking unmatched key ups prevents 68 // the shift key from working properly. 69 private boolean mGotEnterDown; 70 private int mMaxLength; 71 // Keep track of the text before the change so we know whether we actually 72 // need to send down the DOM events. 73 private String mPreChange; 74 private Drawable mBackground; 75 // Variables for keeping track of the touch down, to send to the WebView 76 // when a drag starts 77 private float mDragStartX; 78 private float mDragStartY; 79 private long mDragStartTime; 80 private boolean mDragSent; 81 // True if the most recent drag event has caused either the TextView to 82 // scroll or the web page to scroll. Gets reset after a touch down. 83 private boolean mScrolled; 84 // Gets set to true when the the IME jumps to the next textfield. When this 85 // happens, the next time the user hits a key it is okay for the focus 86 // pointer to not match the WebTextView's node pointer 87 private boolean mOkayForFocusNotToMatch; 88 // Array to store the final character added in onTextChanged, so that its 89 // KeyEvents may be determined. 90 private char[] mCharacter = new char[1]; 91 // This is used to reset the length filter when on a textfield 92 // with no max length. 93 // FIXME: This can be replaced with TextView.NO_FILTERS if that 94 // is made public/protected. 95 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 96 97 /** 98 * Create a new WebTextView. 99 * @param context The Context for this WebTextView. 100 * @param webView The WebView that created this. 101 */ 102 /* package */ WebTextView(Context context, WebView webView) { 103 super(context); 104 mWebView = webView; 105 mMaxLength = -1; 106 } 107 108 @Override 109 public boolean dispatchKeyEvent(KeyEvent event) { 110 if (event.isSystem()) { 111 return super.dispatchKeyEvent(event); 112 } 113 // Treat ACTION_DOWN and ACTION MULTIPLE the same 114 boolean down = event.getAction() != KeyEvent.ACTION_UP; 115 int keyCode = event.getKeyCode(); 116 117 boolean isArrowKey = false; 118 switch(keyCode) { 119 case KeyEvent.KEYCODE_DPAD_LEFT: 120 case KeyEvent.KEYCODE_DPAD_RIGHT: 121 case KeyEvent.KEYCODE_DPAD_UP: 122 case KeyEvent.KEYCODE_DPAD_DOWN: 123 if (!mWebView.nativeCursorMatchesFocus()) { 124 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 125 .onKeyUp(keyCode, event); 126 127 } 128 isArrowKey = true; 129 break; 130 } 131 if (!isArrowKey && !mOkayForFocusNotToMatch 132 && mWebView.nativeFocusNodePointer() != mNodePointer) { 133 mWebView.nativeClearCursor(); 134 // Do not call remove() here, which hides the soft keyboard. If 135 // the soft keyboard is being displayed, the user will still want 136 // it there. 137 mWebView.removeView(this); 138 mWebView.requestFocus(); 139 return mWebView.dispatchKeyEvent(event); 140 } 141 // After a jump to next textfield and the first key press, the cursor 142 // and focus will once again match, so reset this value. 143 mOkayForFocusNotToMatch = false; 144 145 Spannable text = (Spannable) getText(); 146 int oldLength = text.length(); 147 // Normally the delete key's dom events are sent via onTextChanged. 148 // However, if the length is zero, the text did not change, so we 149 // go ahead and pass the key down immediately. 150 if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) { 151 sendDomEvent(event); 152 return true; 153 } 154 155 if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) { 156 if (isPopupShowing()) { 157 return super.dispatchKeyEvent(event); 158 } 159 if (!down) { 160 // Hide the keyboard, since the user has just submitted this 161 // form. The submission happens thanks to the two calls 162 // to sendDomEvent. 163 InputMethodManager.getInstance(mContext) 164 .hideSoftInputFromWindow(getWindowToken(), 0); 165 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); 166 sendDomEvent(event); 167 } 168 return super.dispatchKeyEvent(event); 169 } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { 170 // Note that this handles center key and trackball. 171 if (isPopupShowing()) { 172 return super.dispatchKeyEvent(event); 173 } 174 if (!mWebView.nativeCursorMatchesFocus()) { 175 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 176 .onKeyUp(keyCode, event); 177 } 178 // Center key should be passed to a potential onClick 179 if (!down) { 180 mWebView.shortPressOnTextField(); 181 } 182 // Pass to super to handle longpress. 183 return super.dispatchKeyEvent(event); 184 } 185 186 // Ensure there is a layout so arrow keys are handled properly. 187 if (getLayout() == null) { 188 measure(mWidthSpec, mHeightSpec); 189 } 190 int oldStart = Selection.getSelectionStart(text); 191 int oldEnd = Selection.getSelectionEnd(text); 192 193 boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength; 194 // If we are at max length, and there is a selection rather than a 195 // cursor, we need to store the text to compare later, since the key 196 // may have changed the string. 197 String oldText; 198 if (maxedOut && oldEnd != oldStart) { 199 oldText = text.toString(); 200 } else { 201 oldText = ""; 202 } 203 if (super.dispatchKeyEvent(event)) { 204 // If the WebTextView handled the key it was either an alphanumeric 205 // key, a delete, or a movement within the text. All of those are 206 // ok to pass to javascript. 207 208 // UNLESS there is a max length determined by the html. In that 209 // case, if the string was already at the max length, an 210 // alphanumeric key will be erased by the LengthFilter, 211 // so do not pass down to javascript, and instead 212 // return true. If it is an arrow key or a delete key, we can go 213 // ahead and pass it down. 214 if (KeyEvent.KEYCODE_ENTER == keyCode) { 215 // For multi-line text boxes, newlines will 216 // trigger onTextChanged for key down (which will send both 217 // key up and key down) but not key up. 218 mGotEnterDown = true; 219 } 220 if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) { 221 if (oldEnd == oldStart) { 222 // Return true so the key gets dropped. 223 return true; 224 } else if (!oldText.equals(getText().toString())) { 225 // FIXME: This makes the text work properly, but it 226 // does not pass down the key event, so it may not 227 // work for a textfield that has the type of 228 // behavior of GoogleSuggest. That said, it is 229 // unlikely that a site would combine the two in 230 // one textfield. 231 Spannable span = (Spannable) getText(); 232 int newStart = Selection.getSelectionStart(span); 233 int newEnd = Selection.getSelectionEnd(span); 234 mWebView.replaceTextfieldText(0, oldLength, span.toString(), 235 newStart, newEnd); 236 return true; 237 } 238 } 239 /* FIXME: 240 * In theory, we would like to send the events for the arrow keys. 241 * However, the TextView can arbitrarily change the selection (i.e. 242 * long press followed by using the trackball). Therefore, we keep 243 * in sync with the TextView via onSelectionChanged. If we also 244 * send the DOM event, we lose the correct selection. 245 if (isArrowKey) { 246 // Arrow key does not change the text, but we still want to send 247 // the DOM events. 248 sendDomEvent(event); 249 } 250 */ 251 return true; 252 } 253 // Ignore the key up event for newlines. This prevents 254 // multiple newlines in the native textarea. 255 if (mGotEnterDown && !down) { 256 return true; 257 } 258 // if it is a navigation key, pass it to WebView 259 if (isArrowKey) { 260 // WebView check the trackballtime in onKeyDown to avoid calling 261 // native from both trackball and key handling. As this is called 262 // from WebTextView, we always want WebView to check with native. 263 // Reset trackballtime to ensure it. 264 mWebView.resetTrackballTime(); 265 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 266 .onKeyUp(keyCode, event); 267 } 268 return false; 269 } 270 271 /** 272 * Create a fake touch up event at (x,y) with respect to this WebTextView. 273 * This is used by WebView to act as though a touch event which happened 274 * before we placed the WebTextView actually hit it, so that it can place 275 * the cursor accordingly. 276 */ 277 /* package */ void fakeTouchEvent(float x, float y) { 278 // We need to ensure that there is a Layout, since the Layout is used 279 // in determining where to place the cursor. 280 if (getLayout() == null) { 281 measure(mWidthSpec, mHeightSpec); 282 } 283 // Create a fake touch up, which is used to place the cursor. 284 MotionEvent ev = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 285 x, y, 0); 286 onTouchEvent(ev); 287 ev.recycle(); 288 } 289 290 /** 291 * Determine whether this WebTextView currently represents the node 292 * represented by ptr. 293 * @param ptr Pointer to a node to compare to. 294 * @return boolean Whether this WebTextView already represents the node 295 * pointed to by ptr. 296 */ 297 /* package */ boolean isSameTextField(int ptr) { 298 return ptr == mNodePointer; 299 } 300 301 @Override public InputConnection onCreateInputConnection( 302 EditorInfo outAttrs) { 303 InputConnection connection = super.onCreateInputConnection(outAttrs); 304 if (mWebView != null) { 305 // Use the name of the textfield + the url. Use backslash as an 306 // arbitrary separator. 307 outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\" 308 + mWebView.getUrl(); 309 } 310 return connection; 311 } 312 313 @Override 314 public void onEditorAction(int actionCode) { 315 switch (actionCode) { 316 case EditorInfo.IME_ACTION_NEXT: 317 mWebView.nativeMoveCursorToNextTextInput(); 318 // Preemptively rebuild the WebTextView, so that the action will 319 // be set properly. 320 mWebView.rebuildWebTextView(); 321 // Since the cursor will no longer be in the same place as the 322 // focus, set the focus controller back to inactive 323 mWebView.setFocusControllerInactive(); 324 mOkayForFocusNotToMatch = true; 325 break; 326 case EditorInfo.IME_ACTION_DONE: 327 super.onEditorAction(actionCode); 328 break; 329 case EditorInfo.IME_ACTION_GO: 330 // Send an enter and hide the soft keyboard 331 InputMethodManager.getInstance(mContext) 332 .hideSoftInputFromWindow(getWindowToken(), 0); 333 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 334 KeyEvent.KEYCODE_ENTER)); 335 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 336 KeyEvent.KEYCODE_ENTER)); 337 338 default: 339 break; 340 } 341 } 342 343 @Override 344 protected void onSelectionChanged(int selStart, int selEnd) { 345 if (mWebView != null) { 346 if (DebugFlags.WEB_TEXT_VIEW) { 347 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart 348 + " selEnd=" + selEnd); 349 } 350 mWebView.setSelection(selStart, selEnd); 351 } 352 } 353 354 @Override 355 protected void onTextChanged(CharSequence s,int start,int before,int count){ 356 super.onTextChanged(s, start, before, count); 357 String postChange = s.toString(); 358 // Prevent calls to setText from invoking onTextChanged (since this will 359 // mean we are on a different textfield). Also prevent the change when 360 // going from a textfield with a string of text to one with a smaller 361 // limit on text length from registering the onTextChanged event. 362 if (mPreChange == null || mPreChange.equals(postChange) || 363 (mMaxLength > -1 && mPreChange.length() > mMaxLength && 364 mPreChange.substring(0, mMaxLength).equals(postChange))) { 365 return; 366 } 367 mPreChange = postChange; 368 // This was simply a delete or a cut, so just delete the selection. 369 if (before > 0 && 0 == count) { 370 mWebView.deleteSelection(start, start + before); 371 // For this and all changes to the text, update our cache 372 updateCachedTextfield(); 373 return; 374 } 375 // Find the last character being replaced. If it can be represented by 376 // events, we will pass them to native (after replacing the beginning 377 // of the changed text), so we can see javascript events. 378 // Otherwise, replace the text being changed (including the last 379 // character) in the textfield. 380 TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0); 381 KeyCharacterMap kmap = 382 KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD); 383 KeyEvent[] events = kmap.getEvents(mCharacter); 384 boolean cannotUseKeyEvents = null == events; 385 int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1; 386 if (count > 1 || cannotUseKeyEvents) { 387 String replace = s.subSequence(start, 388 start + count - charactersFromKeyEvents).toString(); 389 mWebView.replaceTextfieldText(start, start + before, replace, 390 start + count - charactersFromKeyEvents, 391 start + count - charactersFromKeyEvents); 392 } else { 393 // This corrects the selection which may have been affected by the 394 // trackball or auto-correct. 395 if (DebugFlags.WEB_TEXT_VIEW) { 396 Log.v(LOGTAG, "onTextChanged start=" + start 397 + " start + before=" + (start + before)); 398 } 399 mWebView.setSelection(start, start + before); 400 } 401 if (!cannotUseKeyEvents) { 402 int length = events.length; 403 for (int i = 0; i < length; i++) { 404 // We never send modifier keys to native code so don't send them 405 // here either. 406 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) { 407 sendDomEvent(events[i]); 408 } 409 } 410 } 411 updateCachedTextfield(); 412 } 413 414 @Override 415 public boolean onTouchEvent(MotionEvent event) { 416 switch (event.getAction()) { 417 case MotionEvent.ACTION_DOWN: 418 super.onTouchEvent(event); 419 // This event may be the start of a drag, so store it to pass to the 420 // WebView if it is. 421 mDragStartX = event.getX(); 422 mDragStartY = event.getY(); 423 mDragStartTime = event.getEventTime(); 424 mDragSent = false; 425 mScrolled = false; 426 break; 427 case MotionEvent.ACTION_MOVE: 428 Spannable buffer = getText(); 429 int initialScrollX = Touch.getInitialScrollX(this, buffer); 430 int initialScrollY = Touch.getInitialScrollY(this, buffer); 431 super.onTouchEvent(event); 432 if (mScrollX != initialScrollX 433 || mScrollY != initialScrollY) { 434 if (mWebView != null) { 435 mWebView.scrollFocusedTextInput(mScrollX, mScrollY); 436 } 437 mScrolled = true; 438 return true; 439 } 440 if (mWebView != null) { 441 // Only want to set the initial state once. 442 if (!mDragSent) { 443 mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY, 444 mDragStartTime); 445 mDragSent = true; 446 } 447 boolean scrolled = mWebView.textFieldDrag(event); 448 if (scrolled) { 449 mScrolled = true; 450 cancelLongPress(); 451 return true; 452 } 453 } 454 return false; 455 case MotionEvent.ACTION_UP: 456 case MotionEvent.ACTION_CANCEL: 457 if (!mScrolled) { 458 // If the page scrolled, or the TextView scrolled, we do not 459 // want to change the selection, and the long press has already 460 // been canceled, so there is no need to call into super. 461 super.onTouchEvent(event); 462 } 463 // Necessary for the WebView to reset its state 464 if (mWebView != null && mDragSent) { 465 mWebView.onTouchEvent(event); 466 } 467 break; 468 default: 469 break; 470 } 471 return true; 472 } 473 474 @Override 475 public boolean onTrackballEvent(MotionEvent event) { 476 if (isPopupShowing()) { 477 return super.onTrackballEvent(event); 478 } 479 if (event.getAction() != MotionEvent.ACTION_MOVE) { 480 return false; 481 } 482 // If the Cursor is not on the text input, webview should handle the 483 // trackball 484 if (!mWebView.nativeCursorMatchesFocus()) { 485 return mWebView.onTrackballEvent(event); 486 } 487 Spannable text = (Spannable) getText(); 488 MovementMethod move = getMovementMethod(); 489 if (move != null && getLayout() != null && 490 move.onTrackballEvent(this, text, event)) { 491 // Selection is changed in onSelectionChanged 492 return true; 493 } 494 return false; 495 } 496 497 /** 498 * Remove this WebTextView from its host WebView, and return 499 * focus to the host. 500 */ 501 /* package */ void remove() { 502 // hide the soft keyboard when the edit text is out of focus 503 InputMethodManager.getInstance(mContext).hideSoftInputFromWindow( 504 getWindowToken(), 0); 505 mWebView.removeView(this); 506 mWebView.requestFocus(); 507 } 508 509 /* package */ void bringIntoView() { 510 if (getLayout() != null) { 511 bringPointIntoView(Selection.getSelectionEnd(getText())); 512 } 513 } 514 515 /** 516 * Send the DOM events for the specified event. 517 * @param event KeyEvent to be translated into a DOM event. 518 */ 519 private void sendDomEvent(KeyEvent event) { 520 mWebView.passToJavaScript(getText().toString(), event); 521 } 522 523 /** 524 * Always use this instead of setAdapter, as this has features specific to 525 * the WebTextView. 526 */ 527 public void setAdapterCustom(AutoCompleteAdapter adapter) { 528 if (adapter != null) { 529 setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); 530 adapter.setTextView(this); 531 } 532 super.setAdapter(adapter); 533 } 534 535 /** 536 * This is a special version of ArrayAdapter which changes its text size 537 * to match the text size of its host TextView. 538 */ 539 public static class AutoCompleteAdapter extends ArrayAdapter<String> { 540 private TextView mTextView; 541 542 public AutoCompleteAdapter(Context context, ArrayList<String> entries) { 543 super(context, com.android.internal.R.layout 544 .search_dropdown_item_1line, entries); 545 } 546 547 /** 548 * {@inheritDoc} 549 */ 550 public View getView(int position, View convertView, ViewGroup parent) { 551 TextView tv = 552 (TextView) super.getView(position, convertView, parent); 553 if (tv != null && mTextView != null) { 554 tv.setTextSize(mTextView.getTextSize()); 555 } 556 return tv; 557 } 558 559 /** 560 * Set the TextView so we can match its text size. 561 */ 562 private void setTextView(TextView tv) { 563 mTextView = tv; 564 } 565 } 566 567 /** 568 * Determine whether to use the system-wide password disguising method, 569 * or to use none. 570 * @param inPassword True if the textfield is a password field. 571 */ 572 /* package */ void setInPassword(boolean inPassword) { 573 if (inPassword) { 574 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 575 TYPE_TEXT_VARIATION_PASSWORD); 576 createBackground(); 577 } 578 // For password fields, draw the WebTextView. For others, just show 579 // webkit's drawing. 580 setWillNotDraw(!inPassword); 581 setBackgroundDrawable(inPassword ? mBackground : null); 582 // For non-password fields, avoid the invals from TextView's blinking 583 // cursor 584 setCursorVisible(inPassword); 585 } 586 587 /** 588 * Private class used for the background of a password textfield. 589 */ 590 private static class OutlineDrawable extends Drawable { 591 public void draw(Canvas canvas) { 592 Rect bounds = getBounds(); 593 Paint paint = new Paint(); 594 paint.setAntiAlias(true); 595 // Draw the background. 596 paint.setColor(Color.WHITE); 597 canvas.drawRect(bounds, paint); 598 // Draw the outline. 599 paint.setStyle(Paint.Style.STROKE); 600 paint.setColor(Color.BLACK); 601 canvas.drawRect(bounds, paint); 602 } 603 // Always want it to be opaque. 604 public int getOpacity() { 605 return PixelFormat.OPAQUE; 606 } 607 // These are needed because they are abstract in Drawable. 608 public void setAlpha(int alpha) { } 609 public void setColorFilter(ColorFilter cf) { } 610 } 611 612 /** 613 * Create a background for the WebTextView and set up the paint for drawing 614 * the text. This way, we can see the password transformation of the 615 * system, which (optionally) shows the actual text before changing to dots. 616 * The background is necessary to hide the webkit-drawn text beneath. 617 */ 618 private void createBackground() { 619 if (mBackground != null) { 620 return; 621 } 622 mBackground = new OutlineDrawable(); 623 624 setGravity(Gravity.CENTER_VERTICAL); 625 // Turn on subpixel text, and turn off kerning, so it better matches 626 // the text in webkit. 627 TextPaint paint = getPaint(); 628 int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG | 629 Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG; 630 paint.setFlags(flags); 631 // Set the text color to black, regardless of the theme. This ensures 632 // that other applications that use embedded WebViews will properly 633 // display the text in password textfields. 634 setTextColor(Color.BLACK); 635 } 636 637 /* package */ void setMaxLength(int maxLength) { 638 mMaxLength = maxLength; 639 if (-1 == maxLength) { 640 setFilters(NO_FILTERS); 641 } else { 642 setFilters(new InputFilter[] { 643 new InputFilter.LengthFilter(maxLength) }); 644 } 645 } 646 647 /** 648 * Set the pointer for this node so it can be determined which node this 649 * WebTextView represents. 650 * @param ptr Integer representing the pointer to the node which this 651 * WebTextView represents. 652 */ 653 /* package */ void setNodePointer(int ptr) { 654 mNodePointer = ptr; 655 } 656 657 /** 658 * Determine the position and size of WebTextView, and add it to the 659 * WebView's view heirarchy. All parameters are presumed to be in 660 * view coordinates. Also requests Focus and sets the cursor to not 661 * request to be in view. 662 * @param x x-position of the textfield. 663 * @param y y-position of the textfield. 664 * @param width width of the textfield. 665 * @param height height of the textfield. 666 */ 667 /* package */ void setRect(int x, int y, int width, int height) { 668 LayoutParams lp = (LayoutParams) getLayoutParams(); 669 if (null == lp) { 670 lp = new LayoutParams(width, height, x, y); 671 } else { 672 lp.x = x; 673 lp.y = y; 674 lp.width = width; 675 lp.height = height; 676 } 677 if (getParent() == null) { 678 mWebView.addView(this, lp); 679 } else { 680 setLayoutParams(lp); 681 } 682 // Set up a measure spec so a layout can always be recreated. 683 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 684 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 685 requestFocus(); 686 } 687 688 /** 689 * Set whether this is a single-line textfield or a multi-line textarea. 690 * Textfields scroll horizontally, and do not handle the enter key. 691 * Textareas behave oppositely. 692 * Do NOT call this after calling setInPassword(true). This will result in 693 * removing the password input type. 694 */ 695 public void setSingleLine(boolean single) { 696 int inputType = EditorInfo.TYPE_CLASS_TEXT 697 | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 698 if (single) { 699 int action = mWebView.nativeTextFieldAction(); 700 switch (action) { 701 // Keep in sync with CachedRoot::ImeAction 702 case 0: // NEXT 703 setImeOptions(EditorInfo.IME_ACTION_NEXT); 704 break; 705 case 1: // GO 706 setImeOptions(EditorInfo.IME_ACTION_GO); 707 break; 708 case -1: // FAILURE 709 case 2: // DONE 710 setImeOptions(EditorInfo.IME_ACTION_DONE); 711 break; 712 } 713 } else { 714 inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 715 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 716 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 717 setImeOptions(EditorInfo.IME_ACTION_NONE); 718 } 719 mSingle = single; 720 setHorizontallyScrolling(single); 721 setInputType(inputType); 722 } 723 724 /** 725 * Set the text for this WebTextView, and set the selection to (start, end) 726 * @param text Text to go into this WebTextView. 727 * @param start Beginning of the selection. 728 * @param end End of the selection. 729 */ 730 /* package */ void setText(CharSequence text, int start, int end) { 731 mPreChange = text.toString(); 732 setText(text); 733 Spannable span = (Spannable) getText(); 734 int length = span.length(); 735 if (end > length) { 736 end = length; 737 } 738 if (start < 0) { 739 start = 0; 740 } else if (start > length) { 741 start = length; 742 } 743 if (DebugFlags.WEB_TEXT_VIEW) { 744 Log.v(LOGTAG, "setText start=" + start 745 + " end=" + end); 746 } 747 Selection.setSelection(span, start, end); 748 } 749 750 /** 751 * Set the text to the new string, but use the old selection, making sure 752 * to keep it within the new string. 753 * @param text The new text to place in the textfield. 754 */ 755 /* package */ void setTextAndKeepSelection(String text) { 756 mPreChange = text.toString(); 757 Editable edit = (Editable) getText(); 758 edit.replace(0, edit.length(), text); 759 updateCachedTextfield(); 760 } 761 762 /** 763 * Update the cache to reflect the current text. 764 */ 765 /* package */ void updateCachedTextfield() { 766 mWebView.updateCachedTextfield(getText().toString()); 767 } 768} 769