使用AppCompactActivity错误地扩展类片段

时间:2015-12-31 09:52:04

标签: android android-fragments fragment

我看到所有重复的问题/答案,但对我来说没有任何一项工作。

Caused by: android.view.InflateException: Binary XML file line #7:  Error inflating class fragment
 at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
 at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
 at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
 at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393)
 at android.app.Activity.setContentView(Activity.java:2166)
 at com.projectemplate.musicpro.activity.SongListActivity.onCreate(SongListActivity.java:166)
 at android.app.Activity.performCreate(Activity.java:6237)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
 at android.app.ActivityThread.-wrap11(ActivityThread.java) 
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
 at android.os.Handler.dispatchMessage(Handler.java:102) 
 at android.os.Looper.loop(Looper.java:148) 
 at android.app.ActivityThread.main(ActivityThread.java:5417) 
 at java.lang.reflect.Method.invoke(Native Method) 

xml文件:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#000"
style="@style/Layout.FillWidthHeight" >


 <fragment
    android:id="@+id/fragmentListSongs"
    android:name="com.projectemplate.musicpro.fragment.ListSongsFragment"
    style="@style/Layout.FillWidthHeight"
    />
</RelativeLayout>

SongListActivity.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

public class SongListActivity extends AppCompatActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
    setContentView(R.layout.activity_main);

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.show(fm.findFragmentById(R.id.fragmentListSongs));
    transaction.commit();
}

运行时在调用fragment时给出的错误。我检查了所有代码,没有发现任何错误。请帮助我......

1 个答案:

答案 0 :(得分:0)

我认为您需要先将片段添加到堆栈中。

 Fragment songs  = new SongsFragment();  //I don't know what you've called it
 FragmentTransaction ft = fragmentManager.beginTransaction();
 ft.add(R.id.fragment_container, songs, tag); //in your activity the content view id
 if (addToBackStack) {
  ft.addToBackStack(tag);
 }
 ft.commit();