2013-03-06 131 views
0

我正在嘗試使用片段,但無法使用它。片段不能正常工作

這是我的主要活動

public class StartingActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.fragmentexample);}} 

這裏的代碼是fragmentexample.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="horizontal" > 

<fragment 
    android:name="com.example.demos.Fragment1" 
    android:id="@+id/idfragment1" 
    android:layout_width="wrap_content" 
    android:layout_height="fill_parent" 
    /> 

<fragment 
    android:name="com.example.demos.Fragment2" 
    android:id="@+id/idfragment2" 
    android:layout_width="0dip" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" 
    /> 

這裏是一流的片段1

public class Fragment1 extends Fragment { 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    return inflater.inflate(R.layout.fragment1, container, false); 
} 

}

,這裏是fragment1.xml

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="This is Fragment1" /> 

</LinearLayout> 

類Fragment2和fragment2.xml只是相同片段1和fragment1.xml

但是這個代碼不工作,並給予錯誤

03-06 13:43:50.011: E/AndroidRuntime(26696): FATAL EXCEPTION: main 
03-06 13:43:50.011: E/AndroidRuntime(26696): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.demos/com.example.demos.StartingActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment 
03-06 13:43:50.011: E/AndroidRuntime(26696): ... 11 more 
+2

請從'FragmentActivity'擴展你的'Activity' ... – 2013-03-06 08:18:02

+0

你是在說StartActitity?我如何從FragmentActivty擴展它? – 2013-03-06 08:21:25

+0

後全堆棧跟蹤 – njzk2 2013-03-06 08:34:09

回答

1

您的活動應擴展FragmentActivity

0

添加默認構造在Fragment1和Fragment2類中。

象下面這樣:

public class Fragment2 extends Fragment { 

    public Fragment2() { 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     return inflater.inflate(R.layout.fragment2, container, false); 
    } 

}

這應該工作。