当我运行我的Fragment项目时,eclipse显示错误。我不知道如何解决它

时间:2015-08-03 15:35:35

标签: android

这是我试图仔细遵循的指示:

http://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/

这是Logcat中出现的第一个错误:

E / MoreInfoHPW_ViewGroup(21404):父视图不是TextView

E / AndroidRuntime(21404):致命异常:主

E / AndroidRuntime(21404):进程:com.example.fragmentstest,PID:21404

E / AndroidRuntime(21404):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.fragmentstest / com.example.fragmentstest.MainActivity}:android.view.InflateException:二进制XML文件行#20:膨胀类片段错误

这是我的MainActivity和activity_main代码:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void selectFrag(View view){
    Fragment fr;
    if (view == findViewById(R.id.button2)){
        fr = new FragmentTwo();
    } else {
        fr = new FragmentOne();
    }
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_place, fr);
    fragmentTransaction.commit();


}  




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

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Fragment No.1"
    android:onClick="selectFrag" />

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Fragment No.2" 
    android:onClick="selectFrag"/>

<fragment 
    android:name="com.example.fragmentstest.FragmentOne"
    android:id="@+id/fragment_place"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>"

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

我终于找到了错误原因。这是一个逻辑错误(很难找到)。 在FragmentOne.java和FragmentTwo.java中,我返回activity_main.xml而不是fragment_one.xml和fragment_two.xml作为源布局。 对不起,如果问题不在我在问题正文中提供的信息中。但至少现在我知道了更多!

以下是示例代码:

   public class FragmentTwo extends Fragment {
   @Override
   public View onCreateView(LayoutInflater inflater,
   ViewGroup container, Bundle savedInstanceState) {

   //I had to use fragment_one instead of activity_main.
   //Such simple mistake took about two days of my time.

  return inflater.inflate(
          R.layout.activity_main, container, false);
  }