【问题标题】:EditText: Avoid getting focus on setText()EditText:避免关注 setText()
【发布时间】:2013-10-17 09:39:29
【问题描述】:

我有一个带有滚动视图的活动,其中包含一些按钮和一个 EditText 所以按钮位于 EditText 组件上方。

通过单击按钮,EditText 组件使用EditText.setText("foo"); 更改其文本值

不幸的是,此调用会将焦点设置到 EditText 组件,因此 ScrollView 将滚动到 EditText 组件(光标闪烁)。

有没有办法避免这种情况?

我尝试过这样做

public void setText(String t){
    editText.setFocusable(false)
    editText.setFocusableInTouchMode(false);
    editText.setText(t);
    editText.setFocusable(true);
    editText.setFocusableInTouchMode(true);
}

但这不起作用,有时setFocusable(true) 没有影响,因此 EditText 不再“可点击”。

【问题讨论】:

  • 尝试在 xml 中更改 EditText 的可聚焦性。
  • 但应该还是可以编辑的
  • 尝试将 textwatcher 侦听器设置为 null 然后检查。
  • 检查我编辑的答案。

标签: android focus android-edittext


【解决方案1】:
editText.clearFocus();

当这个视图想要放弃焦点时调用。

http://developer.android.com/reference/android/view/View.html#clearFocus()

【讨论】:

  • 这是该问题最合适的解决方案。
【解决方案2】:

在您的按钮中使用以下代码

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

参考以下链接

android edittext remove focus after clicking a button

【讨论】:

    【解决方案3】:

    在你的按钮中使用下面的代码......

     InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
    
     inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
    

    【讨论】:

      【解决方案4】:

      在您的 xml 中使用它:

      <EditText
              android:clickable="false" 
              android:cursorVisible="false" 
              android:focusable="false" 
              android:focusableInTouchMode="false">
      </EditText>
      

      edittext.setKeyListener(null);
      

      【讨论】:

        猜你喜欢
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-12
        • 1970-01-01
        相关资源
        最近更新 更多