【问题标题】:How to current focus edittext in android?如何在android中聚焦edittext?
【发布时间】:2012-01-31 11:43:28
【问题描述】:

您好,我想获得当前焦点在按钮单击时的编辑文本,有任何按钮可以做到这一点。

或者,如果活动中有许多编辑文本,则有一种方法可以识别最后修改的编辑文本。

请给我推荐可用的链接或示例代码。

【问题讨论】:

    标签: android android-layout android-emulator android-intent android-widget


    【解决方案1】:

    我采用线性布局并在其中添加自定义 EditText。

        LayoutInflater li = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        for(int i = 0; i < 3; i++) {
            View v = li.inflate(R.layout.addit, null);
            final EditText e = (EditText) v.findViewById(R.id.e1);
            e.addTextChangedListener(new TextWatcher() {
    
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub
    
                }
    
                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                    // TODO Auto-generated method stub
    
                }
    
                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    // TODO Auto-generated method stub
    
                    System.out.println("--change--");
                    mEditText = e;
                    System.out.println(e.getText().toString());
                }
    
            });
            edit_ll.addView(v);
        }
    

    这里的 mEditText 是一个全局变量。

    您可以在活动中的任何位置访问它。并且可以得到你最后写入的editText是什么。

    【讨论】:

      【解决方案2】:

      您可以为所有 EditTexts 添加一个 textWatcher:

      private class CustomTextWatcher implements TextWatcher {
          private EditText mEditText;
      
          public CustomTextWatcher(EditText e) {
              mEditText = e;
          }
      
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {
          }
      
          public void onTextChanged(CharSequence s, int start, int before, int count) {
          }
      
          public void afterTextChanged(Editable s) {
          }
      }
      

      并且可以为您的类设置一个全局变量以包含正在编辑的 editText 引用。

      【讨论】:

      • 请建议我如何添加您的 CustomerTextWatcher 来编辑文本 final EditText tv= new EditText(getContext());
      猜你喜欢
      • 1970-01-01
      • 2012-01-09
      • 2021-04-24
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2015-01-07
      • 1970-01-01
      相关资源
      最近更新 更多