Java 如何在Android中扩展两个类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21459902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Extend Two Classes in Android?
提问by AruLNadhaN
I need to extend Two classes from a Single Class.My class Wants to extend Both ListActivity & MainActivity.
我需要从单个类扩展两个类。我的类想要扩展 ListActivity 和 MainActivity。
I found a question similar to this. But i don't know how to Implement this https://stackoverflow.com/a/5836735/2781359
我发现了一个类似的问题。但我不知道如何实现这个https://stackoverflow.com/a/5836735/2781359
Thanks for your Help.
谢谢你的帮助。
The Class which has to be Extended is ConnectionEditActivity.
必须扩展的类是 ConnectionEditActivity。
public class ConnectionEditActivity extends ListActivity implements OnClickListener
{
public static Connection connectionParam;
private Connection connection;
private Button save;
private EditText name;
private EditText password;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.connection = connectionParam;
this.save = (Button) this.findViewById(R.id.save);
this.save.setOnClickListener(this);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD)
{
// Don't need the Save button on newer devices
android.widget.LinearLayout.LayoutParams a = (LayoutParams) this.save.getLayoutParams();
a.height = 0;
this.save.setLayoutParams(a);
this.save.forceLayout();
}
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
}
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
// Inflate the menu items for use in the action bar
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.connection_edit_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(android.view.MenuItem item)
{
// Handle presses on the action bar items
switch (item.getItemId())
{
case R.id.action_save:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected void onResume()
{
super.onResume();
this.name.setText(this.connection.getName());
this.password.setText(this.connection.getPassword());
}
protected void onPause()
{
super.onPause();
this.connection.setName(this.name.getText().toString());
this.connection.setPassword(this.password.getText().toString());
finish();
}
public void onClick(View v)
{
if (v == this.save)
{
this.finish();
}
}
}
Mainactivity
主要活动
public abstract class MainActivity extends ActionBarActivity
{
protected ListView mDrawerList;
protected DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
String LOG_TAG = "Remote It";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR);
// getSupportActionBar().hide();
setContentView(R.layout.activity_main_drawer);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
private void _initMenu()
{
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems)
{
int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res], "drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
// if (res==1) mItem.counter=12; //it is just an example...
// if (res==3) mItem.counter=3; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
// Second Block
mAdapter.addHeader(R.string.ns_menu_main_header2);
menuItems = getResources().getStringArray(R.array.ns_menu_itemss);
String[] menuItemsIcons = getResources().getStringArray(R.array.ns_menu_items_iconss);
int ress = 0;
for (String item : menuItems)
{
int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcons[ress], "drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
// if (res==1) mItem.counter=12; //it is just an example...
// if (res==3) mItem.counter=3; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle
{
public CustomActionBarDrawerToggle(Activity mActivity, DrawerLayout mDrawerLayout)
{
super(mActivity, mDrawerLayout, R.drawable.ic_drawer, R.string.ns_menu_open, R.string.ns_menu_close);
}
@Override
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle(getString(R.string.ns_menu_close));
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle(getString(R.string.ns_menu_open));
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
mDrawer.closeDrawer(mDrawerList);
switch (position)
{
case 1:
Intent a = new Intent(MainActivity.this, Home.class);
startActivity(a);
break;
case 2:
Intent ac = new Intent(MainActivity.this, ConnectionListActivity.class);
startActivity(ac);
break;
default:
}
}
EDIT
编辑
I need to Extend it.Because the MainActivity has the navigation drawer.Now ConnectionEditActivity
doesn't shows the navigationDrawer nor the ActionBar .But i need to show the ActionBar
Any Suggestions ??
我需要扩展它。因为 MainActivity 有导航抽屉。现在 ConnectionEditActivity 不显示 navigationDrawer 也不显示 ActionBar。但我需要显示 ActionBar
任何建议?
回答by njzk2
You need to start by identifying what parts of MainActivity
you need to inherit from, and what do you need from ListActivity
.
您需要首先确定MainActivity
您需要从哪些部分继承,以及您需要从ListActivity
.
Then, you have various possibilities:
然后,您有多种可能性:
- Trivially, not extending
ListActivity
. ExtendingListActivity
only provides you with utility methods to work with theListView
, but you can totally have aListView
in anActivity
without it being aListActivity
. - Create a utility class that contains extracted methods you need from
MainActivity
and call these methods from both your new class andMainActivity
. - Modify
MainActivity
so that it extendsListActivity
. After all it does contain aListView
(you'd loose theActionBar
thing, though).
- 琐碎,不扩展
ListActivity
. 扩展ListActivity
只为您提供实用的方法来配合工作ListView
,但你完全可以有一个ListView
在Activity
没有它是一个ListActivity
。 - 创建一个实用程序类,其中包含您需要的提取方法,
MainActivity
并从您的新类和MainActivity
. - 修改
MainActivity
使其扩展ListActivity
. 毕竟它确实包含一个ListView
(不过你会弄丢ActionBar
它)。
回答by Or Bar
In Java you can't extend multiple classes, and for a good reason. Take for example what you are trying to accomplish by extending MainActivity
and ListActivity
. In your new class, when you call:
在 Java 中,您不能扩展多个类,这是有充分理由的。以您试图通过扩展MainActivity
和来完成的工作为例ListActivity
。在你的新班级中,当你打电话时:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
}
Which onCreate() are you overriding? The one from ListActivity
, or the one from MainActivity
?
您要覆盖哪个 onCreate()?一从ListActivity
,还是一从MainActivity
?
What the link you posted is saying is that instead of inheriting from another object, you compose your new object of the one you are trying to use. For example:
您发布的链接说的是,您不是从另一个对象继承,而是由您尝试使用的对象组成新对象。例如:
public class NewClass extends OldClass1 {
private OldClass2 mOldClass2 = new OldClass2();
@Override
public methodFromOldClass1() {
}
public methodFromOldClass2() {
mOldClass2.methodFromOldClass2();
}
}
The problem with this approach is that the methods from MainActivity
and ListActivity
are still going to have the same name, which although you can work around, it will become a headache quickly.
这种方法的问题是来自MainActivity
和的方法ListActivity
仍然具有相同的名称,尽管您可以解决这个问题,但很快就会变得令人头疼。
So the problem is a result of how you designed your class hierarchy. You will need to think about what functions you need from MainActivity
, and what functions from ListActivity
and choose how to reimplement your objects.
所以问题是你如何设计你的类层次结构的结果。您将需要考虑您需要使用MainActivity
哪些函数,使用哪些函数ListActivity
并选择如何重新实现您的对象。
My Suggestion, since ListActivity
only makes it slightly easier to work with lists (not that much easier) you can just skip it and implement the code related to the list on your own, and that way you can just extend MainActivity
我的建议,因为ListActivity
只会使使用列表稍微容易一些(不是那么容易),您可以跳过它并自己实现与列表相关的代码,这样您就可以扩展MainActivity