2012-09-13 17 views
0

我將盡我所能發佈相關代碼並清楚地解釋...我正在關注Android上的教程;它是一個ListView應用程序,我現在將其轉換爲碎片。它告訴我將我的課程中的一個從extends ListActivity更改爲extends Activity。這樣做,我的兩個特別針對ListActivity的調用需要改變。我以爲我改變了他們正常的,但我得到這些錯誤(只是列表的頂部):無法在我的MainActivity中啓動活動

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> 

Phew!我認爲這就是所需要的,但如果我確實知道,我可以自己解決這個問題。誰能幫忙?

回答

1

您在下面的行中有問題。

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

從R檔你引用片段,但你要它轉換爲ListView的是你的problem.you可以簡單地解決這個問題如下。

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

+0

當然!我應該發現...但它必須是一個片段;我無法將其更改爲列表視圖。有關我如何能夠完成這項工作的任何想法? – AmberWolfe

+0

好的AmberWolfe我編輯了答案,希望它能幫助你。 –

+0

這有幫助。謝謝! – AmberWolfe

相關問題