2012-12-03 49 views
0

嗨,我是新的android開發。片段不會工作

我使用的片段 - 但我不完全瞭解它是如何工作的。

當我啓動它崩潰的應用程序。

我用Google搜索了很多,但大炮解決這一:(

我有一個活動(MainActivity)必須使用一個片段MainActivity樣子:

public class MainActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
    } 
} 

而且main.xml中包含ListView和一個片段:

<ListView 
    android:id="@+id/myListView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

<fragment class="com.todolist.NewItemFragment" 
    android:id="@+id/titles_fragment" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" /> 

我的片段延伸ListFragment,看起來像:

public class NewItemFragment extends ListFragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    return inflater.inflate(R.layout.new_item_fragment, container, false); 
    } 
} 

而且new_item_fragment.xml樣子:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

<ListView 
    android:id="@+id/myListView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

</LinearLayout> 

我不知道爲什麼它崩潰。我一定誤解了一些東西。 我希望有人在那裏可以幫助 - 不知道該怎麼做:)

THX


我已經導入庫:

android.support.v4.app.FragmentActivity 

並提出在MainActivity類擴展FragmentActivity

它給我下面的錯誤:

enter image description here

+0

後您的logcat的請。 – slezadav

+0

請參閱我在答案中所做的修改。 – Luksprog

回答

1

修改new_item_fragment.xml佈局文件是這樣的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

<ListView 
    android:id="@android:id/list" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

</LinearLayout> 

解決最明顯的錯誤。如果應用程序仍然崩潰,則發佈Logcat,但例外。

此外,當您擴展Activity類時,請確保您只使用SDK中的Fragment相關類(如果在應用程序中註冊了該類,則不包括兼容性包)。這些課程從Honeycomb開始提供。

如果您打算使用FragmentActivity,請確保您使用兼容性套件中的Fragment類(來自FragmentActivity的地方)。

+0

我要在哪裏使用片段類? – Diemauerdk

+0

@ user1093774您可以使用'ListFragment',確保您的'NewItemFragment'類從兼容包中擴展'ListFragment'。檢查你的進口。 – Luksprog

0

嘗試通過如下代碼替換您的片段:

public class NewItemFragment extends ListFragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.new_item_fragment, null, false); 
    } 
}