我正在尝试在每个 Activity 上实现一些代码,不想将代码复制并分页到每个 Activity 中。
最初,我只有一个父 Activity 和代码,然后扩展了所有其他 Activity ,但我无法在 ListActivities 或 ExpandableListActivities 上执行此操作。
我认为这将通过使用接口(interface)类然后让每个 Activity 实现它来完成。然而,当我尝试这样做时,Eclipse 给我一个错误并说要删除方法体。
这是我目前的情况
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public interface MenuOptions {
/**
* Method called when the hardware menu button is called. Uses optionmenu.xml for layout
*/
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.optionmenu, menu);
return true;
}
/**
* Event listener for the options menu. If home is pressed user is sent to home screen. If settings is pressed user is sent to setting screen
* User is passed as an extra
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent nextIntent = null;
switch (item.getItemId()) {
case R.id.home:
Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
nextIntent = new Intent(this, Home.class);
break;
case R.id.settings:
Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
nextIntent = new Intent(this, Settings.class);
break;
}
nextIntent.putExtra("user", user);
startActivity(nextIntent);
return true;
}
}
最佳答案
Java 中的
Interface
类应该只包含方法签名而不包含实现。因此你必须创建一个基类:
public class MenuOptions extends Activity {
/**
* Method called when the hardware menu button is called. Uses optionmenu.xml for layout
*/
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.optionmenu, menu);
return true;
}
/**
* Event listener for the options menu. If home is pressed user is sent to home screen. If settings is pressed user is sent to setting screen
* User is passed as an extra
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent nextIntent = null;
switch (item.getItemId()) {
case R.id.home:
Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
nextIntent = new Intent(this, Home.class);
break;
case R.id.settings:
Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
nextIntent = new Intent(this, Settings.class);
break;
}
nextIntent.putExtra("user", user);
startActivity(nextIntent);
return true;
}
}
以及您的 Activity :
public class YourActivity extends MenuOptions {
/*...*/
}
关于java - 使用接口(interface)实现所有 Activity 的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8521079/