Java 结合 ListActivity 和 ActionBarActivity
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20524008/
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
Combining ListActivity and ActionBarActivity
提问by
I am currently building for a minimum SDK
of 10, so I have to use the android-support-v7-appcompat
library to implement ActionBar
. I have setup the ActionBar
, but I want to now add a ListActivity
, however this requires extending my class and Java doesn't have multiple inheritance
. What should I do?
我目前正在构建至少SDK
10 个,所以我必须使用android-support-v7-appcompat
库来实现ActionBar
. 我已经设置了ActionBar
,但我现在想添加一个ListActivity
,但是这需要扩展我的类,而 Java 没有多个inheritance
. 我该怎么办?
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 items for use in the action bar
MenuInflater inflater = getMenuInflater();
getSupportActionBar().setIcon(R.drawable.ic_action_search);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
}
采纳答案by athor
ListActivity hasn't been ported to AppCompat. Probably because you should consider it 'deprecated', and instead use a ListFragment.
ListActivity 尚未移植到 AppCompat。可能是因为您应该将其视为“已弃用”,而是使用 ListFragment。
Fragments will work with a ActionBarActivity, just make sure they are fragments from the support library.
片段将与 ActionBarActivity 一起使用,只需确保它们是来自支持库的片段。
Have a read through thislink about fragments.
阅读有关片段的此链接。
For your use case, I would just define the fragment in xml.
对于您的用例,我只会在 xml 中定义片段。
回答by KVISH
The easiest way to do this is to use a ListFragment
inside of the ActionBarActivity
. I did it like this:
要做到这一点,最简单的方法是使用一个ListFragment
内部ActionBarActivity
。我是这样做的:
public class MyActivity extends ActionBarActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
MyFragment fragment = new MyFragment();
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
finish();
break;
}
default: {
break;
}
}
return true;
}
public static class MyFragment extends ListFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
public void onListItemClick(ListView listView, View view, int position, long id) {
...
}
}
}
This way you don't even need an xml for it, and it works well.
这样你甚至不需要一个 xml,它运行良好。