gpt4 book ai didi

android - 启用/禁用操作栏菜单项

转载 作者:IT老高 更新时间:2023-10-28 22:13:50 26 4
gpt4 key购买 nike

我已取消并保存操作栏菜单项。

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/saveButton"
android:showAsAction="always"
android:title="@string/save"
android:visible="true">

</item>
<item android:id="@+id/cancelButton"
android:showAsAction="always"
android:title="@string/cancel"
android:visible="true">
</item>

</menu>

我想在 Activity 开始时禁用保存菜单项。

我的 Activity 代码 -

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_project);

EditText projectName = (EditText) findViewById(R.id.editTextProjectName);
projectName.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
configureSaveButton(s);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
@Override
public void afterTextChanged(Editable s) {}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.addprojectmenu, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = (MenuItem) findViewById(R.id.saveButton);
item.setEnabled(false);
return super.onPrepareOptionsMenu(menu);
}

private void configureSaveButton(CharSequence s){
String text = null;
if(s != null){
text = s.toString();
}
if(text != null && text.trim().length() != 0){

}else{

}
}

所以我在这里尝试做的是,最初当 Activity 开始时,保存菜单项应该被禁用,当 editext 包含一些文本时,它应该被启用。

我不确定 configureSaveButton 方法中 if else 中的代码应该是什么。另外,我最初如何禁用保存菜单项。

我在 onPrepareOptionsMenu 中得到空指针异常。

我使用的是安卓 4.1

最佳答案

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.addprojectmenu, menu);

menu.getItem(0).setEnabled(false); // here pass the index of save menu item
return super.onPrepareOptionsMenu(menu);

}

只需在准备时间充气并在充气菜单后禁用无需inflateoncreateoptionemenu时间,或者您可以在从 onCreateOptionMenu 膨胀后使用最后两行代码.

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

menu.getItem(0).setEnabled(false); // here pass the index of save menu item
return super.onPrepareOptionsMenu(menu);

}

关于android - 启用/禁用操作栏菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14169040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com