简体   繁体   English

获取以编程方式创建的视图标签

[英]get view tag created programmatically

In onCreate() method, i'm creating a TextEdit with a tag programmatically like so: 在onCreate()方法中,我正在以编程方式创建带有标签的TextEdit,如下所示:

EditText et = new EditText(getApplicationContext());
et.setTag(field.getFieldId());
et.setBackgroundResource(R.drawable.textbox);
et.setTextColor(getResources().getColor(R.color.noir));

parentLayout.addView(et);

In afterTextChanged() method , i want to retrieve that EditText tag to get the text entered by user. 在afterTextChanged()方法中,我想检索该EditText标记以获取用户输入的文本。

I've tried this code, but i'm getting NullPointerException: 我已经尝试过此代码,但是却收到NullPointerException:

EditText et = (EditText) parentLayout.findViewWithTag("4249");
String strValue = et.getText().toString();

Can you help me please !! 你能帮我吗 !!

Thank you. 谢谢。

Well, i found a solution myself. 好吧,我自己找到了解决方案。

1) Create an EditText programmatically, set a custom TextWatcher and add the EditText to it: 1)以编程方式创建一个EditText,设置一个自定义TextWatcher并将EditText添加到其中:

EditText et = new EditText(getApplicationContext());
                    et.setTag(field.getFieldId());
                    et.setBackgroundResource(R.drawable.textbox);
                    et.setTextColor(getResources().getColor(R.color.noir));
et.addTextChangedListener(new CustomTextWatcher(et));

2) Create a custom TextWatcher: 2)创建一个自定义TextWatcher:

private class CustomTextWatcher implements TextWatcher{

          private EditText editText;

          private MyTextWatcher(EditText editText) {
           this.editText = editText;
          }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }
        @Override
        public void afterTextChanged(Editable s) {

            String strValue = this.editText.getText().toString();
            Log.d("afterTextChanged", strValue);

        }
    }

Hope that help other developers. 希望对其他开发人员有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM