InstantiationException:尝试实例化不是片段的类myapp.VideoListFragment

时间:2017-03-19 06:27:41

标签: java android android-fragments android-youtube-api

我想在我的项目中制作YoutubeThumbnail视图...我正在使用列表视图查看我的YouTube视频列表..但是我收到错误,因为3天我用谷歌搜索但没有找到。当我点击activity_main.xml中的按钮时,它应该打开test.xml片段..我的所有视频列表都位于..应用程序崩溃..我已经给了下面的logcat ..请帮帮我我这样做是为了约3天:(

主要Activity.java

public class MainActivity extends AppCompatActivity {

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

    Button btn = (Button) findViewById(R.id.button);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            android.app.FragmentManager fm = getFragmentManager();
            fm.beginTransaction().add(R.id.content_frame, new test()).commit();
        }
    });
}

test.java

public class test extends Fragment {

View rootview;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = inflater.inflate(R.layout.test,container,false);
return rootview;
}

}

VideoListAdapter.java

public class VideoListAdapter extends BaseAdapter implements YouTubeThumbnailView.OnInitializedListener {

private Context mContext;
private Map<View, YouTubeThumbnailLoader> mLoaders;

public VideoListAdapter(final Context context) {
    mContext = context;
    mLoaders = new HashMap<>();
}

@Override
public int getCount() {
    return YouTubeContent.ITEMS.size();
}

@Override
public Object getItem(int position) {
    return YouTubeContent.ITEMS.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    VideoHolder holder;

    //The item at the current position
    final YouTubeContent.YouTubeVideo item = YouTubeContent.ITEMS.get(position);

    if (convertView == null) {
        //Create the row
        final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.row_layout, parent, false);

        //Create the video holder
        holder = new VideoHolder();

        //Set the title
        holder.title = (TextView) convertView.findViewById(R.id.textView_title);
        holder.title.setText(item.title);

        //Initialise the thumbnail
        holder.thumb = (YouTubeThumbnailView) convertView.findViewById(R.id.imageView_thumbnail);
        holder.thumb.setTag(item.id);
        holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this);

        convertView.setTag(holder);
    } else {
        //Create it again
        holder = (VideoHolder) convertView.getTag();
        final YouTubeThumbnailLoader loader = mLoaders.get(holder.thumb);

        if (item != null) {
            //Set the title
            holder.title.setText(item.title);

            //Setting the video id can take a while to actually change the image
            //in the meantime the old image is shown.
            //Removing the image will cause the background color to show instead, not ideal
            //but preferable to flickering images.
            holder.thumb.setImageBitmap(null);

            if (loader == null) {
                //Loader is currently initialising
                holder.thumb.setTag(item.id);
            } else {
                //The loader is already initialised
                //Note that it's possible to get a DeadObjectException here
                try {
                    loader.setVideo(item.id);
                } catch (IllegalStateException exception) {
                    //If the Loader has been released then remove it from the map and re-init
                    mLoaders.remove(holder.thumb);
                    holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this);

                }
            }

        }
    }
    return convertView;
}


@Override
public void onInitializationSuccess(YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
    mLoaders.put(view, loader);
    loader.setVideo((String) view.getTag());
}

@Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
    final String errorMessage = errorReason.toString();
    Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show();
}


static class VideoHolder {
    YouTubeThumbnailView thumb;
    TextView title;
}

VideoListFragment.java

public class VideoListFragment extends ListFragment {

/**
 * Empty constructor
 */
public VideoListFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new VideoListAdapter(getActivity()));
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

    final Context context = getActivity();
    final String DEVELOPER_KEY = getString(R.string.DEVELOPER_KEY);
    final YouTubeContent.YouTubeVideo video = YouTubeContent.ITEMS.get(position);

    switch (position) {
        case 0:
            //Check whether we can actually open YT
            if (YouTubeIntents.canResolvePlayVideoIntent(context)) {
                //Opens the video in the YouTube app
                startActivity(YouTubeIntents.createPlayVideoIntent(context, video.id));
            }
            break;
        case 1:
            if (YouTubeIntents.canResolvePlayVideoIntentWithOptions(context)) {
                //Opens in the YouTube app in fullscreen and returns to this app once the video finishes
                startActivity(YouTubeIntents.createPlayVideoIntentWithOptions(context, video.id, true, true));
            }
            break;
        case 2:
            //Issue #3 - Need to resolve StandalonePlayer as well
            if (YouTubeIntents.canResolvePlayVideoIntent(context)) {
                //Opens in the StandAlonePlayer, defaults to fullscreen
                startActivity(YouTubeStandalonePlayer.createVideoIntent(getActivity(),
                        DEVELOPER_KEY, video.id));
            }
            break;
        case 3:
            //Issue #3 - Need to resolve StandalonePlayer as well
            if (YouTubeIntents.canResolvePlayVideoIntentWithOptions(context)) {
                //Opens in the StandAlonePlayer but in "Light box" mode
                startActivity(YouTubeStandalonePlayer.createVideoIntent(getActivity(),
                        DEVELOPER_KEY, video.id, 0, true, true));
            }
         break;

    }
}

YouTubeContent.java

public class YouTubeContent {

/**
 * An array of YouTube videos
 */
public static List<YouTubeVideo> ITEMS = new ArrayList<>();

/**
 * A map of YouTube videos, by ID.
 */
public static Map<String, YouTubeVideo> ITEM_MAP = new HashMap<>();

static {
    addItem(new YouTubeVideo("tttG6SdnCd4", "Open in the YouTube App"));
    addItem(new YouTubeVideo("x-hH_Txxzls", "Open in the YouTube App in fullscreen"));
    addItem(new YouTubeVideo("TTh_qYMzSZk", "Open in the Standalone player in fullscreen"));
    addItem(new YouTubeVideo("tttG6SdnCd4", "Open in the Standalone player in \"Light Box\" mode"));

}

private static void addItem(final YouTubeVideo item) {
    ITEMS.add(item);
    ITEM_MAP.put(item.id, item);
}

/**
 * A POJO representing a YouTube video
 */
public static class YouTubeVideo {
    public String id;
    public String title;

    public YouTubeVideo(String id, String content) {
        this.id = id;
        this.title = content;
    }

    @Override
    public String toString() {
        return title;
    }
}

activity_main.xml中

<android.support.constraint.ConstraintLayout 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.bucky.myapp.MainActivity">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

row_layout.xml

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

<!-- Video Thumbnail -->
<com.google.android.youtube.player.YouTubeThumbnailView
    android:id="@+id/imageView_thumbnail"
    android:layout_width="85dp"
    android:layout_height="85dp"
    android:layout_alignParentLeft="true"
    android:layout_margin="5dp"
    android:background="#000"
    android:scaleType="centerCrop" />


<!-- Video Title -->
<TextView
    android:id="@+id/textView_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@id/imageView_thumbnail"
    android:layout_toRightOf="@id/imageView_thumbnail"
    android:paddingBottom="5dp"
    android:paddingRight="5dp"
    android:text="video_list_title"
    android:textColor="@android:color/black"
    android:textSize="15sp" />

test.java

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/video_list"
    android:name="com.example.bucky.myapp.VideoListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    tools:context=".VideoListActivity"
    tools:layout="@android:layout/list_content" />

`

logcat的。

  Process: com.example.bucky.myapp, PID: 18751
                                                                     android.view.InflateException: Binary XML file line #5: Error inflating class fragment
                                                                         at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
                                                                         at com.example.bucky.myapp.test.onCreateView(test.java:19)
                                                                         at android.app.Fragment.performCreateView(Fragment.java:2114)
                                                                         at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:904)
                                                                         at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082)
                                                                         at android.app.BackStackRecord.run(BackStackRecord.java:834)
                                                                         at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1469)
                                                                         at android.app.FragmentManagerImpl$1.run(FragmentManager.java:452)
                                                                         at android.os.Handler.handleCallback(Handler.java:739)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                         at android.os.Looper.loop(Looper.java:145)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6946)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
                                                                      Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.bucky.myapp.VideoListFragment that is not a Fragment
                                                                         at android.app.Fragment.instantiate(Fragment.java:620)
                                                                         at android.app.Fragment.instantiate(Fragment.java:596)
                                                                         at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2125)
                                                                         at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:178)
                                                                         at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) 
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:511) 
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:415) 
                                                                         at com.example.bucky.myapp.test.onCreateView(test.java:19) 
                                                                         at android.app.Fragment.performCreateView(Fragment.java:2114) 
                                                                         at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:904) 
                                                                         at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082) 
                                                                         at android.app.BackStackRecord.run(BackStackRecord.java:834) 
                                                                         at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1469) 
                                                                         at android.app.FragmentManagerImpl$1.run(FragmentManager.java:452) 
                                                                         at android.os.Handler.handleCallback(Handler.java:739) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                         at android.os.Looper.loop(Looper.java:145) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6946) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
                                                                      Caused by: java.lang.ClassCastException
                                                                         at android.app.Fragment.instantiate(Fragment.java:620) 
                                                                         at android.app.Fragment.instantiate(Fragment.java:596) 
                                                                         at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2125) 
                                                                         at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:178) 
                                                                         at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740) 
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:813) 
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:511) 
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:415) 
                                                                         at com.example.bucky.myapp.test.onCreateView(test.java:19) 
                                                                         at android.app.Fragment.performCreateView(Fragment.java:2114) 
                                                                         at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:904) 
                                                                         at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082) 
                                                                         at android.app.BackStackRecord.run(BackStackRecord.java:834) 
                                                                         at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1469) 
                                                                         at android.app.FragmentManagerImpl$1.run(FragmentManager.java:452) 
                                                                         at android.os.Handler.handleCallback(Handler.java:739) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                         at android.os.Looper.loop(Looper.java:145) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6946) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

1 个答案:

答案 0 :(得分:0)

尝试加载实际的ListFragment

setContentView(R.layout.activity_main);

Button btn = (Button) findViewById(R.id.button);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        getFragmentManager()
           .beginTransaction()
           .add(R.id.content_frame, new VideoListFragment()) 
           .commit();
    }
});