我想知道如何在活动中添加片段(通过xml(最好是)或java),而不会崩溃你的应用。我无法添加它,我看了很多教程,但无法理解。每次我将片段添加到主要活动时,我的应用程序都会崩溃。
MainActivity.java
package com.example.mashh.fragments;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mashh.fragments.MainActivity"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="70dp"
android:name="com.example.mashh.fragments.BlankFragment"
tools:layout="@layout/fragment_blank" />
</LinearLayout>
BlankFragment.java
package com.example.mashh.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {@link Fragment} subclass.
*/
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}
fragment_blank.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mashh.fragments.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
答案 0 :(得分:0)
<fragment
android:id="@+id/blank_fragment"
android:layout_width="match_parent"
android:layout_height="70dp"
android:name="com.example.mashh.fragments.BlankFragment"
tools:layout="@layout/fragment_blank" />
xml add android:id