android - 在对话框中时未触发 EditText 监听器

标签 android dialog listener android-edittext

我在 android 中创建了一个自定义对话框,其中包含一个 EditText 和一个 ListView。当我选择任何项目时, ListView onItemClickListener 被正确触发,但我的 EditText 的监听器不是这种情况。

这是我的代码:

EditText filterEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

LayoutInflater factory = LayoutInflater.from(this);
View content = factory.inflate(R.layout.dialog_layout, null);
filterEditText = (EditText) content
        .findViewById(R.id.filterEditText);
filterEditText.addTextChangedListener(txtListener);

............


    TextWatcher txtListener = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {

            filterEditText.setText("text entered");
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }
    };

最佳答案

我正要删除帖子,但我决定把解决方案放在一起,以防有人遇到同样的问题。

我通过将我的代码从 onCreate 移动到我创建对话框的方法中解决了这个问题:

public void createLocationsDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    builder.setTitle("Choose a location");

    LayoutInflater factory = LayoutInflater.from(MainActivity.this);
    View content = factory.inflate(R.layout.dialog_layout, null);

    ListView locationsList = (ListView) content
            .findViewById(R.id.locationsListView);
    filterEditText = (EditText) content
            .findViewById(R.id.filterEditText);

    ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(
            MainActivity.this, android.R.layout.simple_list_item_1,
            data.getName());
    locationsList.setAdapter(modeAdapter);

    builder.setView(content);

    locationsDialog = builder.create();

    locationsList.setOnItemClickListener(listItemClicked);
    filterEditText.addTextChangedListener(txtListener);

    locationsDialog.show();
}

关于android - 在对话框中时未触发 EditText 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16325139/

相关文章:

android - 在android中 Activity 动画结束后如何调用函数

Jquery 对话框打开事件未触发

java - TextToSpeech SynthesizeToFile 何时完成?

android - SQLite连接池 : A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/metrics.db' was leaked

android - Android Util.Base64默认编码行为是否一致

Javascript:关闭模态且焦点不返回屏幕

ios - 更改 AlertController 的布局

android - 一个类(class)的多个听众

networking - 当两台计算机监听同一个端口并且路由器通过该端口接收数据包时会发生什么

java - android 中未出现警报对话框