android - 无法将 fragment View 切换到主视图

标签 android android-layout android-fragments android-view

我无法尝试将 fragment 中的内容放入 android studio 的主视图中。

应用编译并运行。但是当我在抽屉导航(滑动菜单)中选择一个项目到带有 fragment 的列表中的项目时:它是空白的。

我的 fragment 包含一个嵌入式 YouTube 播放器。

logCat 没有显示错误...

从我的代码来看 - 我在看哪里错了??

这是主要的 Activity :

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
            case 4:
                mTitle = getString(R.string.title_section4);
                break;
            case 5:
                mTitle = getString(R.string.title_section5);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }

    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            //displayView(position);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        /* @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        } */

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

}

这是 fragment 类:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

public class MasjidAlHaramFragment extends Fragment implements YouTubePlayer.OnInitializedListener {

    public String API_KEY = "xxxxxxxxxxxxxxxxxxxxx";

    //http://youtu.be/<VIDEO_ID>
    //final String VIDEO_ID = "4OoKpZWJASY";
    public String VIDEO_ID_2 = "VopbGPJVkzM";

    public MasjidAlHaramFragment () {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_masjidharam, container, false);

        //http://youtu.be/<VIDEO_ID>
        //final String VIDEO_ID = "4OoKpZWJASY";
        //final String VIDEO_ID_2 = "VopbGPJVkzM";

        /** Initializing YouTube player view **/
        YouTubePlayerView youTubePlayerView = null;
        if (youTubePlayerView != null)
            youTubePlayerView = (YouTubePlayerView) getView().findViewById(R.id.youtube_player);
        youTubePlayerView.initialize(API_KEY, this);

        return rootView;
    }

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            /** attaching layout xml **/
            //setContentView(R.layout.activity_main);

        }

    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
            //Toast.makeText(this,"Failured to Initialize!", Toast.LENGTH_LONG).show();
        }

        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
            /** add listeners to YouTubePlayer instance **/
            player.setPlayerStateChangeListener(playerStateChangeListener);
            player.setPlaybackEventListener(playbackEventListener);

            /** Start buffering **/
            if (!wasRestored) {
                player.cueVideo(VIDEO_ID_2);
            }
        }

        YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {

            @Override
            public void onBuffering(boolean arg0) {
            }

            @Override
            public void onPaused() {
            }

            @Override
            public void onPlaying() {
            }

            @Override
            public void onSeekTo(int arg0) {
            }

            @Override
            public void onStopped() {
            }

        };

        YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {

            @Override
            public void onAdStarted() {
            }

            @Override
            public void onError(YouTubePlayer.ErrorReason arg0) {
            }

            @Override
            public void onLoaded(String arg0) {
            }

            @Override
            public void onLoading() {
            }

            @Override
            public void onVideoEnded() {
            }

            @Override
            public void onVideoStarted() {
            }
        };
}

这是 XML View

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_player"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:padding="5dp" />

</RelativeLayout>

谢谢。

铁螳螂7x

最佳答案

您需要在 fragment 的 onCreateView 方法中调用 super.onCreateView(...) 才能正确绘制 fragment 。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

此外,我建议您执行以下操作,因为存在一些逻辑错误:

View rootView = inflater.inflate(R.layout.fragment_masjidharam, container, false);

YouTubePlayerView youTubePlayerView = null;
// THIS IS ALWAYS FALSE. Comment it out or else it'll never get set.  
// if (youTubePlayerView != null)

youTubePlayerView = (YouTubePlayerView) rootView.findViewById(R.id.youtube_player);

// Check for not-null here.
if(youTubePlayerView != null) {
    youTubePlayerView.initialize(API_KEY, this);
}

关于android - 无法将 fragment View 切换到主视图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32804322/

相关文章:

android - Activity 跳转开始时的动画

java - fragment 布局中的 MapView(android maps api v2)不显示

Android意外按钮点击ViewPager滑动

javascript - 使用 JavaScript 在 Android 中显示来自 HTML 的图片

android - 为 Android WebView 启用 WebGL 支持

android - 向 RadioGroup 和 Radiobutton 添加过渡动画

android - 如何在android中应用Straight Skeleton Algorithm

Android 刷新操作栏和 fragment 更改标题

java - 为什么 onLongPress() 不像所有其他 SimpleOnGestureListener 那样返回 boolean 值?

java - 即使convertView不为null,convertView.findViewById也会返回null