当EditText不为空时启用Action MenuItem

时间:2013-11-06 11:12:35

标签: java android android-actionbar menuitem screen-orientation

我想要完成的是当我的EditText为空时,应该禁用Action Menu中的MenuItem。我在onCreateOptionsMenu方法中对菜单进行了膨胀,然后在onPrepareOptionsMenu方法中禁用了Send按钮并保存了对Menu的引用,以便我可以在onCreate方法中设置的TextWatcher中使用它。

Menu myMenu;

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

    // Set up TextWatcher
    EditText ed = (EditText) findViewById(R.id.new_task_title);
    ed.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d("MYLOG", "This is onTextChanged event");

            if (s == null || s.length() == 0) {
                myMenu.findItem(R.id.action_send).setEnabled(false);
            }
            else {
                myMenu.findItem(R.id.action_send).setEnabled(true);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            Log.d("MYLOG", "This is beforeTextChanged event");
        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d("MYLOG", "This is afterTextChanged event");
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.new_task, menu);

    Log.d("MYLOG", "This is onCreateOptionsMenu event");
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    Log.d("MYLOG", "This is onPrepareOptionsMenu event");

    // Save reference to the menu
    myMenu = menu;

    // Disable Send Button
    myMenu.findItem(R.id.action_send).setEnabled(false);

    return true;
}

此代码运行正常,并且完全按照直到更改屏幕方向。据我所知,当发生这种情况时,活动会被销毁并再次创建。问题是,当重新创建活动时,会调用 onTextChanged beforeTextChanged afterTextChanged 方法,就好像用户更改了文本一样(他没有)。 此外,所有这三种方法都被称为 onCreateOptionsMenu onPrepareOptionsMenu 方法之前的,这基本上意味着在 onTextChanged 我正在尝试访问那时甚至不存在的菜单对象。当然,这会导致空指针异常和应用程序崩溃。

为了说明这种行为,这是改变屏幕方向时CatLog的样子。

11-06 11:55:39.142: D/MYLOG(32527): This is beforeTextChanged event
11-06 11:55:39.147: D/MYLOG(32527): This is onTextChanged event
11-06 11:55:39.147: D/MYLOG(32527): This is afterTextChanged event
11-06 11:55:39.207: D/MYLOG(32527): This is onCreateOptionsMenu event
11-06 11:55:39.207: D/MYLOG(32527): This is onPrepareOptionsMenu event
11-06 11:55:39.232: D/MYLOG(32527): This is onPrepareOptionsMenu event

所以我的问题是,我在这里遗漏了什么吗?对于我想要实现的目标,还有其他更好的方法吗?或者,当屏幕方向发生变化时,我有什么方法可以让Android 调用onTextChanged?

1 个答案:

答案 0 :(得分:0)

如果使用为横向模式定义的布局更改方向,应用程序的行为是什么? 尝试在/ res文件夹下创建layout-land文件夹,并将您的布局文件复制粘贴到该文件夹​​。