EditText侦听器在对话框中未触发

时间:2013-05-01 19:38:09

标签: android dialog listener android-edittext

我在android中创建了一个包含EditText和ListView的自定义对话框。当我选择任何Item时,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
        }
    };

1 个答案:

答案 0 :(得分:4)

我准备删除帖子,但我决定提出解决方案以防任何人遇到同样的问题。

我通过将我的代码从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();
}