无法在我的MainActivity中启动活动

时间:2012-09-13 03:29:13

标签: android exception

我会尽力发布相关代码并清楚解释......我正在关注Android的教程;它是一个ListView应用程序,我现在转换为片段。它告诉我将我的一个课程从extends ListActivity更改为extends Activity。这样做,我特别对ListActivity的两个调用需要改变。我以为我正确地改变了它们,但是我得到了这些错误(只是列表的顶部):

W/dalvikvm(4486): threadid=1: thread exiting with uncaught exception (group=0x40209760)
E/AndroidRuntime(4486): FATAL EXCEPTION: main
E/AndroidRuntime(4486): java.lang.RuntimeException: Unable to start activity 
    ComponentInfo{com.example.testing/com.example.testing.MainActivity}:
    java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.widget.ListView

我的主要活动代码,我认为相关的部分是:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_fragment);

    ListView lv = (ListView) findViewById(R.id.list_fragment);
    lv.setAdapter(ArrayAdapter.createFromResource(getApplicationContext(),
            R.array.tut_titles, R.layout.activity_main));
    final String[] links = getResources().getStringArray(R.array.tut_links);

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick......

        }
    });
}

lv变量是新的,用它做的两个调用曾经是特定于ListActivity的。到目前为止,我的list_fragment只是这个:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="com.example.testing.UrlFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/list_fragment">
</fragment>

唷!我认为这就是所需要的,但如果我确切知道,我可能会自己解决这个问题。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您遇到以下问题。

ListView lv = (ListView) findViewById(R.id.list_fragment);

从R文件中引用片段,但是你要将它转换为ListView,这是你的问题。你可以简单地解决它。如下所示。

1)创建一个扩展Fragment的类。

public static class YourFragmentClass extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

2)在你的活动课上。

YourFragmentClass fragment = new YourFragmentClass ();
fragmentTransaction.add(R.id.list_fragmentr, fragment);
fragmentTransaction.commit();

3)更多check this out

相关问题