简体   繁体   中英

get view tag created programmatically

In onCreate() method, i'm creating a TextEdit with a tag programmatically like so:

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.

I've tried this code, but i'm getting 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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