我正在尝试在Utils.java
文件中实现我的菜单。好吧,到目前为止一切顺利,菜单显示应该尽管如此,但是当我点击任何菜单项时,应用程序停止工作。我似乎没有找到问题所在,我将非常感谢你的建议。我的菜单,工具和活动文件的代码如下:
Utils.java
package com.package.name;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class Utils extends Activity{
private Context _context;
public Utils(Context context){
this._context = context;
}
public void menuSwitch(int item) {
switch (item) {
case R.id.menu_one:
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
case R.id.menu_two:
startActivity(new Intent(getApplicationContext(),
MessageActivity.class));
case R.id.menu_three:
startActivity(new Intent(getApplicationContext(),
LocateActivity.class));
case R.id.menu_four:
startActivity(new Intent(this,
AboutActivity.class));
}
}
}
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item android:id="@+id/menu_one" android:title="@string/menu_one" />
<item android:id="@+id/menu_two" android:title="@string/menu_two" />
<item android:id="@+id/menu_three" android:title="@string/menu_three" />
<item android:id="@+id/menu_four" android:title="@string/menu_four" />
</menu>
menuActivity.java
package com.package.name;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DatabaseActivity extends ListActivity {
Utils util;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
util = new Utils(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
util.menuSwitch(item.getItemId());
return true;
}
}
答案 0 :(得分:0)
您正在使用Util类的 startactivity ,但它应该是菜单所在的类,因此您应该使用
_context.startactivity(new Intent(_context,wahteverclass.class))
答案 1 :(得分:0)
您不应该延长Utils
课程。用这个替换你的代码。
public class Utils{
private Context _context;
public Utils(Context context){
this._context = context;
}
public void menuSwitch(int item) {
switch (item) {
case R.id.menu_one:
_context.startActivity(new Intent(_context.getApplicationContext(),
MainActivity.class));
case R.id.menu_two:
_context.startActivity(new Intent(_context.getApplicationContext(),
MessageActivity.class));
case R.id.menu_three:
_context.startActivity(new Intent(_context.getApplicationContext(),
LocateActivity.class));
case R.id.menu_four:
_context.startActivity(new Intent(_context.getApplicationContext(),
AboutActivity.class));
}
}
}