2012-05-01 118 views
2

我知道這類問題問很多時間,但還沒有人給出完美的答案。Android將光標從一個EditText移動到另一個EditText?

我有一個問題:

我想從EditText1 **移動到另一個** EditText2。 我已經檢測到editText1,但如何將光標移動到editText2。

總之,我不得不將我的光標位置從一個editText1直接移動到另一個EditText2。

+0

當您想將光標從Edittext1移動到Edittext2 –

+0

@KrishnakantDalal當我在第一個editText1中檢測到一些特殊字符時,它將移動到下一個editText2。 我已經成功地檢測到特殊字符,但不知道如何實時移動它。 –

回答

6

我遇到了這種類型的問題,並找到如下解決方案。

這裏我有兩個EDITTEXT,

如果我按「一」,我將光標移動到下一個步驟。我使用下面的代碼來完成它。

final EditText editText = (EditText) findViewById(R.id.editText1); 

     editText.setOnKeyListener(new OnKeyListener() { 

      @Override 
      public boolean onKey(View v , int keyCode , KeyEvent event) { 

        EditText editText2 = (EditText) findViewById(R.id.editText2); 

       // TODO Auto-generated method stub 
       if (keyCode == event.KEYCODE_A) { 

        Selection.setSelection((Editable) editText2.getText(),editText.getSelectionStart()); 
        editText2.requestFocus(); 
       } 

       return true; 
      } 
     }); 

讓我知道你是否面臨任何錯誤。 如果我的回答對你有幫助,請接受它並評分爲upvote。

+0

謝謝你的回答。 有時它在我登錄真實設備時無法使用。 –

+0

我在這裏找到了更好的解決方案http://stackoverflow.com/questions/12418324/android-move-cursor-from-one-edittext-to-another-one-if-click-any-letter-in-fiel –

1

以下是一個工作示例,希望對您有所幫助。

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 

    <EditText 
     android:id="@android:id/text1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Some string of text" 
     /> 

    <EditText 
     android:id="@android:id/text2" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Some string of text" 
     /> 

    <Button 
     android:id="@android:id/button1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Button" 
     /> 

</LinearLayout> 

類:

public class Example extends Activity { 
    TextView text1; 
    TextView text2; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     text1 = (EditText) findViewById(android.R.id.text1); 
     text2 = (EditText) findViewById(android.R.id.text2); 
     Button button = (Button) findViewById(android.R.id.button1); 

     button.setOnClickListener(new OnClickListener() { 
      public void onClick(View view) { 
       Selection.setSelection((Editable) text2.getText(), text1.getSelectionStart()); 
       text2.requestFocus(); 
      } 
     }); 
    } 
} 
+0

感謝您的回答。我希望它成爲實時場景。 當我檢測到一些特殊字符時,我的第一個editText1光標將被移動到下一個editText2。 我已經成功地檢測到特殊字符,但不知道如何在Realtime中移動它。 –

1

設置onKeyListener檢測壓在每一個按鍵檢查你的病情,當你的條件將滿足套EDITTEXT財產edittext2.requestFocus關鍵( );

0

我測試了所有以前的代碼段,並發現所有工作正常。但是我發現用正確的edittext對象調用「requestFocus()」也是可行的。按照問題所述,ans可以是:

edittext2.requestFocus();

這對我來說工作得很好。如果我錯了,請糾正我。

相關問題