我的操作栏中有一个奇怪的问题,有一个共享按钮,但是当应用程序启动时首次点击它时它不起作用但是在它首先工作没有任何问题。这是我的代码。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.about_us);
dialog.setTitle("About Us");
dialog.setCancelable(true);
TextView textView = (TextView)dialog.findViewById(R.id.aboutus);
textView.setText("blah blah blah");
Button button = (Button)dialog.findViewById(R.id.close);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
return false;
}
});
break;
case R.id.share_action: item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.TEXT", "blah blah blah");
localIntent.putExtra("android.intent.extra.SUBJECT", "FLAMES");
startActivity(Intent.createChooser(localIntent, "Share"));
return false;
}
});
break;
}
return false;}
这是截图。App Screenshot
我忘了Action Bar Menu_items的行为都是一样的。 请给出任何解决方案。
答案 0 :(得分:0)
单击与其关联的菜单项时,将自动调用OnMenuItemClickListener,单击任何菜单项时,onOptionsItem选择函数也将被调用。
所以你不需要两者兼顾。将任务设置在OnMenuItemClickListener内或onOptionsItemSelected内。
例如,onOptionsItemSelected必须如下所示:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.about_us);
dialog.setTitle("About Us");
dialog.setCancelable(true);
TextView textView = (TextView)dialog.findViewById(R.id.aboutus);
textView.setText("blah blah blah");
Button button = (Button)dialog.findViewById(R.id.close);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
return false;
break;
case R.id.share_action:
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.TEXT", "blah blah blah");
localIntent.putExtra("android.intent.extra.SUBJECT", "FLAMES");
startActivity(Intent.createChooser(localIntent, "Share"));
return false;
break;
}
return false;}