ActionBar无法正常工作

时间:2013-12-16 05:59:41

标签: android android-actionbar

我需要一些关于Action栏工作的指导。实际上点击操作栏MenuItem。必须将当前活动移至另一个活动。但它什么也没做。甚至没有任何错误。我使用了以下代码:

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.home:
            try {
                openSearch();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

private void openSearch() throws IOException{
    val=address(location.getLatitude(), location.getLongitude());
    Intent intnt=new Intent(getApplicationContext(),SendSms.class);
    intnt.putExtra("loct", val);
    startActivity(intnt); 
}

3 个答案:

答案 0 :(得分:0)

使用MenuInflater inflater = getSupportMenuInflater();

如果您使用的是android主页按钮,则ID为android.R.id.home。在这种情况下,请确保getSupportActionBar().setDisplayHomeAsUpEnabled(true);中有onCreate

编辑 - 确保您已导入以下内容:

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;

答案 1 :(得分:0)

将此代码放在onCreate方法中:

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

    // creating Actionbar
    ActionBar actionBar = getActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.show();
    ...

}

然后将此代码放在onCreate:

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
    case R.id.home:
        try {
            openSearch();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

private void openSearch() throws IOException{
val=address(location.getLatitude(), location.getLongitude());
Intent intnt=new Intent(getApplicationContext(),SendSms.class);
intnt.putExtra("loct", val);
startActivity(intnt); 
}

答案 2 :(得分:0)

这段代码很完美。这段代码没有任何问题。 Actionbar按钮因为它正在接收的空值而无法正常工作。而null值仅仅是因为一些硬件问题..此代码没有任何问题,谢谢