【问题标题】:How to remove main layout from being in every fragment如何从每个片段中删除主要布局
【发布时间】:2015-08-26 14:23:08
【问题描述】:

在我的 MainActivity 中,我有“setContentView(R.layout.activity_main)”。这个 activity_main 布局包含一个 VideoView。

activity_main 没有在任何片段中使用; 当我切换到片段时,我看不到视频(这很好),但如果我点击屏幕,则会弹出视频选项(播放、暂停等)(不好)。 由于“setContentView(R.layout.activity_main)”,我假设 main_activity 位于每个片段的下方?

我需要只在一个片段中显示视频而不影响任何其他片段。但是,如果我尝试从 activity_main 中删除 VideoView 并在片段布局中识别它(即 fragment_one ),我得到一个 NullPointerException。同样,我认为这是因为“setContentView(R.layout.activity_main)”。我在想 java 代码中引用的视图必须在 activity_main 中标识 (id="@+id/video_view")?

这个问题的解决方案可能非常简单,但我似乎无法找到任何解决该问题的信息。我当然是新手,所以请多多包涵。

这是我的 MainActivity:

public class MainActivity extends AppCompatActivity {
    //used in VideoView
    private VideoView myVideoView;
    private int position = 0;
    private ProgressDialog progressDialog;
    private MediaController mediaControls;

String[] LabelMenu = {"Home","Flight Tracker"};
@Override
//Allows the use of icons in overflow-dropdown
protected boolean onPrepareOptionsPanel(View view, Menu menu) {
    if (menu != null) {
        if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
            try {
                Method m = menu.getClass().getDeclaredMethod(
                        "setOptionalIconsVisible", Boolean.TYPE);
                m.setAccessible(true);
                m.invoke(menu, true);
            } catch (Exception e) {
                Log.e(getClass().getSimpleName(), "onMenuOpened...unable to set icons for overflow menu", e);
            }
        }
    }
    return super.onPrepareOptionsPanel(view, menu);
}
//***START OF GOTOURL REFERENCES***
public void goToUS (View view) {
    goToUrl ( "http://10.100.1.200/imsg_weather_radar/weather_radar_united_states.html");
}

public void goToSW (View view) {
    goToUrl( "http://10.100.1.200/imsg_weather_radar/weather_radar_southwest_us.html");
}

public void goToSE (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_southeast_us.html");
}

public void goToNW (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_northwest_us.html");
}

public void goToWP (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_west_pacific.html");
}

public void goToSP (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_south_pacific.html");
}

public void goToCC (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_carolina_coast.html");
}

public void goToWA (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_western_atlantic.html");
}

public void goToEU (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_eastern_us.html");
}

public void goToEGF (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_east_gulf_florida.html");
}

public void goToGM (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_gulf_of_mexico.html");
}

public void goToWGT (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_west_gulf_texas.html");
}

public void goToCI (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_caribbean_islands.html");
}

public void goToMX (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_mexico.html");
}

public void goToCA (View view) {
    goToUrl("http://10.100.1.200/imsg_weather_radar/weather_radar_central_america.html");
}

//***END OF GOTOURL REFERENCES***
private void goToUrl (String url) {
    Uri uriUrl = Uri.parse(url);
    Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
    startActivity(launchBrowser);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set the main layout of activity
    setContentView(R.layout.activity_main);
    //set the media controller buttons

    if (mediaControls == null) {
            mediaControls = new MediaController(MainActivity.this);
        }
        //initialize the VideoView
        myVideoView = (VideoView) findViewById(R.id.video_view);
        // create a progress bar while the video file is loading
        progressDialog = new ProgressDialog(MainActivity.this);
        // set a title for the progress bar
        progressDialog.setTitle("IAWS");
        // set a message for the progress bar
        progressDialog.setMessage("Loading...");
        //set the progress bar not cancelable on users' touch
        progressDialog.setCancelable(false);
        // show the progress bar
        progressDialog.show();

        try {
            //set the media controller in the VideoView
            myVideoView.setMediaController(mediaControls);
            //set the uri of the video to be played
            myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.iaws));
        } catch (Exception e) {
            if(e.getMessage()!=null) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
    }
    myVideoView.requestFocus();
    //setOnPreparedListener in order to know when the video file is ready for playback
    myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer mediaPlayer) {
            // close the progress bar and play the video
            progressDialog.dismiss();
            //if we have a position on savedInstanceState, the video playback should start from here
            myVideoView.seekTo(position);
            if (position == 0) {
                //remove comments if you want video to start automatically
                //myVideoView.start();
            } else {
                //coming from a resumed activity, video playback will be paused
                myVideoView.pause();
            }
        }
    });

    final ActionBar actionBar = getSupportActionBar();
    // Specify that a dropdown list should be displayed in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    // Hide the title
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayUseLogoEnabled(false);
    //Adding an ImageView to Action Bar
    actionBar.setDisplayOptions(actionBar.getDisplayOptions()
            | ActionBar.DISPLAY_SHOW_CUSTOM);
    ImageView imageView = new ImageView(actionBar.getThemedContext());
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    imageView.setImageResource(R.drawable.imsg_blue_logo_rsz);
    ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
            | Gravity.CENTER_VERTICAL);
    layoutParams.rightMargin = 40;
    layoutParams.bottomMargin=10;
    imageView.setLayoutParams(layoutParams);
    actionBar.setCustomView(imageView);
    // Specify a SpinnerAdapter to populate the dropdown list.
    ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(actionBar.getThemedContext(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.labelMenu));
    //2nd Spinner dropdown
    /**
    Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
    mySpinner.setAdapter(new MyCustomAdapter(MainActivity.this, R.layout.row, LabelMenu));
     **/
    actionBar.setListNavigationCallbacks(spinnerMenu,
            // Provide a listener to be called when an item is selected.
            new ActionBar.OnNavigationListener() {
                public boolean onNavigationItemSelected(int position, long id) {
                    // Take action here, e.g. switching to the
                    // corresponding fragment.
                    FragmentTransaction tx = getFragmentManager().beginTransaction();
                    switch (position) {
                        case 0:
                            tx.replace(android.R.id.content, new FirstFragment());
                            break;
                        case 1:
                            tx.replace(android.R.id.content, new SecondFragment());
                            break;
                        case 2:
                            tx.replace(android.R.id.content, new ThirdFragment());
                            break;
                        case 3:
                            tx.replace(android.R.id.content, new FourthFragment());
                            break;
                        case 4:
                            tx.replace(android.R.id.content, new FifthFragment());
                            break;
                        default:
                            break;
                    }
                    tx.commit();
                    return true;
                }
            });
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    // Use onSaveInstanceState in order to store the video playback position for orientation change
    savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());
    myVideoView.pause();
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // Use onRestoreInstanceState in order to play the video playback from the stored position
    position = savedInstanceState.getInt("Position");
    myVideoView.seekTo(position);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
    super.onOptionsItemSelected(item);
    switch(item.getItemId()){
        case R.id.about:
            aboutMenuItem();
            break;
        case R.id.settings:
            settingsMenuItem();
            break;
        case R.id.search:
            searchMenuItem();
            break;
    }
    return true;
}
//Configure "about" function
private void aboutMenuItem(){
    new AlertDialog.Builder(this)
            .setTitle("App & Copyright Info")
            .setMessage("Version 1.0" + "\n" + "Property of I.M. Systems Group, Inc.")
            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();{

    }
}
//Configure "settings" function
private void settingsMenuItem(){
    new AlertDialog.Builder(this)
            .setTitle("Settings")
            .setMessage("Language: English" + "\n" + "Degrees Fahrenheit Selected" + "\n" +
                    "Show Airports" + "\n" + "Speed: KM/H" )
            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();{

    }
}
//Configure "search" function
private void searchMenuItem(){
    new AlertDialog.Builder(this)
            .setTitle("Search")
            .setMessage("This is an about AlertDialog")
            .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).show();{

    }

}

}

我希望此片段专门显示视频。 现在,fragment 会很好地显示它们指定的布局,但是如果您在任何布局中点击屏幕,main_activity 的 VideoView 中的视频选项就会弹出(这很糟糕)。几乎都以相同的方式编码;它们的不同之处仅在于它们引用了不同的布局:

/**
 * Created by ansaripours on 8/19/2015.
 */
public class FirstFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        return (FrameLayout) inflater.inflate(R.layout.fragment_one, container, false);
    }

}

这是我的 main_activity.xml。看来这里要标识ViewVideo,因为setContentView中引用了它,否则我得到一个NullPointerException:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:background="#E1F4FF"
    android:paddingTop="?android:attr/actionBarSize"
    tools:context=".MainActivity">

    <!-- implementing swipeable pages
    <edu.dartmouth.cs.actiontabs.view.SlidingTabLayout
        android:id="@+id/tab"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/tab"/>
        -->
    <!--
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:padding="100"/>-->
    <!--
        <Spinner
            android:id="@+id/spinner"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" /> -->
    <!--
        <ImageView
            android:src="@drawable/rsz_sampleweather"
            android:id="@+id/cover_view"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop"
         />
         -->
    <VideoView
        android:id="@+id/video_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"/>

</FrameLayout>

最后,这是 FirstFragment 类引用的布局。它实际上与 main_activity.xml 相同(没有 cmets)。然而,就像我说的,如果我从 main_activity.xml 中删除 VideoView,我会得到一个 NullPointerException。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:background="#E1F4FF"
    android:paddingTop="?android:attr/actionBarSize"
    tools:context=".MainActivity">

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"/>

</FrameLayout>

请随时提出任何问题。任何见解将不胜感激。

【问题讨论】:

  • 让我试着理解你,你想要一个包含 videoView 的片段。首先不要把VideoView放在activity layout中,放在fragment layout中。其次,如果您点击您的设备活动,则会重新创建。如果您的活动被重新创建,您必须检查 VideoView 是否为空,如果是,则另一个没有 VideoView 的片段处于活动状态。

标签: android android-layout android-fragments android-activity


【解决方案1】:

首先,我建议您阅读有关如何使用 Fragments 的 Android 开发者页面:http://developer.android.com/guide/components/fragments.html

您应该能够在 activity_main.xml 中为片段定义一个容器,并创建一个单独的片段来保存您的 VideoView,可以使用 FragmentTransaction 将其替换为另一个片段。

【讨论】:

  • 谢谢!我认为我的 activity_main.xml 中没有片段容器这一事实是主要问题。通常,当我尝试从 activity_main.xml 中删除 VideoView 时,我会收到 NullPointerException。当我添加指向我的 FirstFragment(引用 fragment_one.xml)的片段容器时,它停止抛出 NullPointerException。这绝对是正确的方向。
  • 很高兴听到这个消息!如果这回答了您的问题,请接受答案
  • 很好的解释!!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 2019-08-21
  • 2011-01-09
  • 2022-08-19
  • 2015-07-13
相关资源
最近更新 更多