Android:向TabHost添加ListActivity会导致ClassCastException

时间:2011-03-29 17:49:03

标签: android listactivity android-tabhost

使用Google提供的示例,我已经成功创建了一个TabHost。

    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, SearchListActivity.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("search").setIndicator("Search",
                      res.getDrawable(R.drawable.icon))
                  .setContent(intent);

    tabHost.addTab(spec);

public class SearchListActivity extends ListActivity

但是,如果我尝试将ListActivity添加到TabHost,则会导致ClassCast异常:

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.companyName.appName/com.companyName.appName.MainActivity}:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.companyName.appName/com.companyName.appName.SearchListActivity}:
java.lang.ClassCastException: android.app.Application

是否无法将ListActivity添加到TabHost?

2 个答案:

答案 0 :(得分:1)

我是通过以下方式做到的:

public class ActivityTab extends TabActivity{
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final TabHost tabHost = getTabHost();

    tabHost.addTab(tabHost.newTabSpec("tab1")
            .setIndicator("Title 1")
            .setContent(new Intent(this, ListActivity_1.class)));

    tabHost.addTab(tabHost.newTabSpec("tab2")
            .setIndicator("Title 2")
            .setContent(new Intent(this, ListActivity_2.class)));
}}

对于ListActivity_1和ListActivity_2类,您只需编写:

    public class ListActivity_1 extends ListActivity { 
    private String[] mStrings = {"Item 1", "Item 2", "Item 3"};
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (Application_VarnePoti)getApplication();
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, mStrings));
    }}

答案 1 :(得分:0)

可以将任何活动添加到TabActivity中,您是否在清单中声明了ListActivity? 你能把TabActivity声明吗?