有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java实例化异常:尝试实例化一个类myapp。VideoListFragment不是片段

我想在我的项目中创建YoutubeThumbnail视图。。。我正在使用列表视图查看我的youtube视频列表。。但我在谷歌上搜索了三天,却发现了错误。当我点击活动_main中的按钮时。应该打开测试的xml。xml片段。。我所有的视频列表都在哪里。。应用程序崩溃。。我已经给出了下面的日志。。请帮帮我,我这样做大约3天:(

主要活动。爪哇

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) {
            安卓.app.FragmentManager fm = getFragmentManager();
            fm.beginTransaction().add(R.id.content_frame, new test()).commit();
        }
    });
}

测试。爪哇

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;
}

}

视频列表适配器。爪哇

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;
}

视频列表片段。爪哇

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。爪哇

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;
    }
}

主要活动。xml

<安卓.support.constraint.ConstraintLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
tools:context="com.example.bucky.myapp.MainActivity">

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

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

</FrameLayout>

排版。xml

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

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


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

测试。爪哇

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

`

Logcat

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

共 (1) 个答案

  1. # 1 楼答案

    尝试加载实际的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();
        }
    });