Android 使用滑动选项卡布局的片段

Android 使用滑动选项卡布局的片段,android,android-fragments,android-tabs,fragmentmanager,Android,Android Fragments,Android Tabs,Fragmentmanager,问候。。。。我是android新手,我正在制作一个应用程序,在一个选项卡上显示一张地图,上面有路线,在另一个选项卡上显示路线导航说明。。。。我按照教程使用三个选项卡完成了滑动选项卡布局。。以前我在一个单独的应用程序中显示了带有路线的地图。现在我想在第二个选项卡中显示它 我是否必须为每个片段关联单独的活动来实现这一点,如果是,那么如何实现这一点 我试图在tab2片段中处理map,但我一直在努力实现这一点,因为当我试图用getMap()初始化它时,googleMap对象中的值会变为null 我的主要

问候。。。。我是android新手,我正在制作一个应用程序,在一个选项卡上显示一张地图,上面有路线,在另一个选项卡上显示路线导航说明。。。。我按照教程使用三个选项卡完成了滑动选项卡布局。。以前我在一个单独的应用程序中显示了带有路线的地图。现在我想在第二个选项卡中显示它

我是否必须为每个片段关联单独的活动来实现这一点,如果是,那么如何实现这一点

我试图在tab2片段中处理map,但我一直在努力实现这一点,因为当我试图用
getMap()
初始化它时,googleMap对象中的值会变为null

我的主要活动代码是:

package com.example.rafaqatrasool.optiroute;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ActionBarActivity {


    // Declaring Your View and Variables

    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[]={"Home","Map","Directions"};
    int Numboftabs =3;

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



        // Creating The Toolbar and setting it as the Toolbar for the activity

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);



        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);

    }



    @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_main, 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);
    }
}
我的ViewPagerAdaper代码是

package com.example.rafaqatrasool.optiroute;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

/**
 * Created by Rafaqat Rasool on 5/26/2015.
 */
public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


    // Build a Constructor and assign the passed Values to appropriate values in the class
    public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);

        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;

    }

    //This method return the fragment for the every position in the View Pager
    @Override
    public Fragment getItem(int position) {

        if (position == 0) // if the position is 0 we are returning the First tab
        {
            Tab1 tab1 = new Tab1();
            return tab1;
        }else if(position == 1){
            Tab2 tab2 = new Tab2();
            return tab2;

        }
        else             // As we are having 3 tabs if the position is now 1 it must be 2 so we are returning third tab
        {
            Tab3 tab3 = new Tab3();
            return tab3;
        }


    }

    // This method return the titles for the Tabs in the Tab Strip

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    // This method return the Number of tabs for the tabs Strip

    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}
我想在地图上使用的第二个选项卡的代码是

package com.example.rafaqatrasool.optiroute;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;


/**
 * Created by Rafaqat Rasool on 5/26/2015.
 */
public class Tab2 extends Fragment {

    GoogleMap googleMap;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.tab_2, container, false);

        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

        // Showing status
        if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
            dialog.show();

        }else if(googleMap == null){
            Log.d("IN ON ACTIVITY CREATED ","Looking for the fragment");
            googleMap= ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        }
        if(googleMap!=null) googleMap.setMyLocationEnabled(true);
    }
}
在这里,当使用getMap()初始化时,我在googleMap对象中得到null

googleMap=((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}
日志:

05-31 09:01:44.357    9546-9546/com.example.rafaqatrasool.optiroute E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.rafaqatrasool.optiroute, PID: 9546
    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
            at com.example.rafaqatrasool.optiroute.Tab2.onActivityCreated(Tab2.java:47)
            at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1797)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:979)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
            at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1072)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:918)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1440)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.
05-31 09:01:54.805    9546-9546/com.example.rafaqatrasool.optiroute I/Process﹕ Sending signal. PID: 9546 SIG: 9
表2的xml是

<?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">


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


</RelativeLayout>

我在谷歌上搜索了很多,现在我很沮丧,我来这里寻求帮助。。。我是android新手,我不知道如何解决这个问题


**如果您尚未找到问题,请任何人帮助我***/p>如果您尚未找到问题,请不要初始化
onActivityCreated
方法中的片段的任何属性。尽可能避免在代码中使用ActivityCreated方法。如果属性是由活动实现的接口,则在
onAttach
方法中进行初始化。 在您的情况下,我建议使用
FrameLayout
而不是fragment标记,并在膨胀视图后在
onCreateView
方法中动态添加谷歌地图。您应该使用
view.findViewById
,然后用片段替换视图。
你应该看看,以便更好地理解

您是仅在模拟器上尝试此操作,还是在真实设备上也尝试此操作?谷歌地图往往无法在模拟器上运行。您找到解决方案了吗??。。如果是,请分享。谢谢