菜单点击项目事件

时间:2014-11-01 18:42:33

标签: android events menu

我添加了3个菜单项:设置 / 关于退出。 正如您在代码中看到的那样,我使用退出按钮关闭应用程序,当我按关于按钮打开新活动时,我希望这样做。我该怎么做?

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

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

    }


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

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;

        } else if (id == R.id.Exit){

            finish();
            return true;

        }
        return super.onOptionsItemSelected(item);
    }

}

3 个答案:

答案 0 :(得分:0)

if(id == R.id.action_masterz_yuris_about){
    Intent openAboutActivityIntent = new Intent(this, MasterZYurisAboutActivity.class);
    startActivity(openAboutActivityIntent);
}

答案 1 :(得分:0)

试用此代码

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;

    } else if (id == R.id.Exit){

        finish();
        return true;

    }else if (id == R.id.about){

        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
        return true;

    }
    return super.onOptionsItemSelected(item);
}

答案 2 :(得分:0)

action_settings 在此代码中代表什么?

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    int id = item.getItemId();

   if (id == R.id.action_settings)
    {
        return true;
    }

    return super.onOptionsItemSelected(item);
}