java - 从操作栏中选择时如何在容器中显示 fragment ?

标签 java android google-maps android-fragments android-actionbar

我的应用程序现在由一个带有操作栏微调器的 Google map 实现组成。当我选择导航栏上的项目时,如何实例化 fragment ?简而言之,我试图在单击其中一个选项时显示一个屏幕。我已经实现了 onNavigationItemSelected() 函数,但我不知道从哪里获取它。这是我的代码。

package com.example.andrew.ubair4;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.OnMapReadyCallback;


public class Ubair extends ActionBarActivity implements ActionBar.OnNavigationListener, OnMapReadyCallback{

    /**
     * The serialization (saved instance state) Bundle key representing the
     * current dropdown position.
     */
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    private GoogleMap googleMap; // Might be null if Google Play services APK is not available.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ubair);

        // Set up the action bar to show a dropdown list.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        // Set up the dropdown list navigation in the action bar.
        actionBar.setListNavigationCallbacks(
                // Specify a SpinnerAdapter to populate the dropdown list.
                new ArrayAdapter<String>(
                        actionBar.getThemedContext(),
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1,
                        new String[]{
                                getString(R.string.title_section1),
                                getString(R.string.title_section2),
                                getString(R.string.title_section3),
                        }),
                this);
        driverOrdersList.newInstance("hi","hi");

        SupportMapFragment  nMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
        googleMap = nMap.getMap();
        googleMap.setMyLocationEnabled(true);

    }



    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Restore the previously serialized current dropdown position.
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getSupportActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Serialize the current dropdown position.
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
                getSupportActionBar().getSelectedNavigationIndex());
    }


    @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_ubair, menu);
        return true;
    }

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

    @Override
    public boolean onNavigationItemSelected(int position, long id) {
        // When the given dropdown item is selected, show its contents in the
        // container view.
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
        return true;
    }


    @Override
    public void onMapReady(GoogleMap map) {
        LatLng sydney = new LatLng(-33.867, 151.206);

        map.setMyLocationEnabled(true);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

        map.addMarker(new MarkerOptions()
                .title("Sydney")
                .snippet("The most populous city in Australia.")
                .position(sydney));
    }
    /**
     * 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_ubair, container, false);
            return rootView;
        }
*/

    }


}

这是我的 xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Ubair"
    tools:ignore="MergeRootFrame" >

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</FrameLayout>

ScreenShot

最佳答案

嗨,在 xml 中,我通常这样构建 fragment :

<FrameLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/container"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:ignore="MergeRootFrame" />

然后在 Activity 中:

phf = PlaceHolderFragment.newInstance();
if (savedInstanceState == null)
{
    getFragmentManager().beginTransaction().add(R.id.container, phf).commit();
}

但在你的情况下你想替换它们,所以在你的微调监听器中你可以这样做:

phf = AccountFragment.newInstance(position, this);
fragmentManager.beginTransaction().replace(R.id.container, accountFragment).commit();

我根据您的评论进行编辑:

@Override
public boolean onNavigationItemSelected(int position, long id) {

    switch(position)
    {
        case 0:
        fragment0 = Fragment0.newInstance();
        fragmentManager.beginTransaction().replace(R.id.container, fragment0).commit();
        break;

        case 1:
        fragment1 = Fragment1.newInstance();
        fragmentManager.beginTransaction().replace(R.id.container, fragment1).commit();
        break;

        //etc...
    }

    return true;
}

或者您可以使用 Activity 的属性声明 fragment ,并仅在回调中替换它们。

关于java - 从操作栏中选择时如何在容器中显示 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29936325/

相关文章:

java - 混合泛型类型变量以在 Java 中实现类型安全的映射函数

java - 如何在运行时更改 TextView 的样式

android - 如何在 Android 中顺利平移 GoogleMap?

java - 我如何在android中将位图转换为PDF格式

java - 使用 TwitterStream 检索推文语言或按语言过滤

android - 在过渡期间使新 Activity 出现在旧 Activity 后面

javascript - AngularJS/GoogleMaps(始终隐藏标记)

javascript - 从 HTML 内部调用 JavaScript?

java - 如何将默认的水平进度条更改为垂直?

android - 排除或覆盖 AAR list