简体   繁体   English

如何通过按钮从另一个片段选项卡打开片段选项卡

[英]How can i open a fragment tab from another fragment tab via button

I have 3 tabs that extent fragment.我有 3 个选项卡,该范围片段。 the second fragment (extends fragment implements locationListener) have a map with bus station markers (works perfect).I want from first tab via a button open the second fragment in order to get the position of marker(latlng).第二个片段(扩展片段实现locationListener)有一张带有公交车站标记的地图(完美无缺)。我想通过按钮从第一个选项卡打开第二个片段以获得标记(latlng)的位置。 My problem is that i can not do that with intent (startActivityforresult) because is not an activity.我的问题是我不能用意图 (startActivityforresult) 这样做,因为它不是活动。 Could you please anyone help me with this issue?你能请任何人帮助我解决这个问题吗?

firstfragment.class第一个片段.class

public class FirstTab extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.first, container, false);

    Button btnFrom;
    Button btnTo;


 // Getting reference to Buttons From&To
    btnFrom = ( Button ) view.findViewById(R.id.btn_from);
    btnTo = ( Button ) view.findViewById(R.id.btn_to);

 // click listener on Buttons From
    btnFrom.setOnClickListener(new OnClickListener() {

  @Override
   public void onClick(View v) {
    // move to secondfragment   

     }
   });

 // click listener on Buttons To
   btnTo.setOnClickListener(new OnClickListener() {

    @Override
     public void onClick(View v) {

     // move to secondfragment                 

     }     
   });

   return view;  
   } 
 }

first.xml第一个.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"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="14dp"
    android:layout_marginTop="25dp"
    android:text="Destination from:"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/btn_showroute"
    android:layout_width="wrap_content"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:text="Show My Route" />

<Button
    android:id="@+id/btn_to"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_below="@+id/btnSpeak1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:text="@string/str_btn_to" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_centerVertical="true"
    android:text="Destination To:"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/btn_from"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_alignLeft="@+id/btn_to"
    android:layout_below="@+id/btnSpeak"
    android:layout_marginTop="29dp"
    android:text="@string/str_btn_from" />

SecondTab.class第二个标签类

 public class SecondTab extends Fragment implements LocationListener{

GoogleMap mGoogleMap;
Spinner mSprPlaceType;
Spinner mSprRadius;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
String[] mRadius=null;
String[] mRadiusType=null;

double mLatitude=0;
double mLongitude=0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.second, container, false);


    // Array of place types
    mPlaceType = getResources().getStringArray(R.array.place_type);

   // Array of radius
    mRadius = getResources().getStringArray(R.array.radius);

    mRadiusType = getResources().getStringArray(R.array.radius_type);

    // Array of place type names
    mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

    // Creating an array adapter with an array of Place types
    // to populate the spinner
    ArrayAdapter<?> adapter = new ArrayAdapter<Object>(getActivity(), android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
    ArrayAdapter<?> radapter = new ArrayAdapter<Object>(getActivity(), android.R.layout.simple_spinner_dropdown_item, mRadius);

    // Getting reference to the Spinner
    mSprPlaceType = (Spinner) view.findViewById(R.id.spr_place_type);
    mSprRadius = (Spinner) view.findViewById(R.id.spr_radius);

    // Setting adapter on Spinner to set place types
    mSprPlaceType.setAdapter(adapter);
    mSprRadius.setAdapter(radapter);


    Button btnFind;

    // Getting reference to Find Button
    btnFind = ( Button ) view.findViewById(R.id.btn_find);

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());

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

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

    }else { // Google Play Services are available

        // Getting reference to the SupportMapFragment
        SupportMapFragment fragment = ( SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

        // Getting Google Map
        mGoogleMap = fragment.getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);

     // Getting LocationManager object from System Service LOCATION_SERVICE

  //  LocationManager locationManager = (LocationManager) 
  getSystemService(LOCATION_SERVICE);
        LocationManager locationManager = (LocationManager) 
  getActivity().getSystemService(Context.LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            onLocationChanged(location);
        }

        locationManager.requestLocationUpdates(provider, 20000, 0, this);

        // Setting click event lister for the find button
        btnFind.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                int selectedPosition = mSprRadius.getSelectedItemPosition();
                String type = mRadiusType[selectedPosition];

                StringBuilder sb = new  
                StringBuilder("https://maps.googleapis.com/maps/api/
                place/nearbysearch/json?");
                sb.append("location="+mLatitude+","+mLongitude);
                sb.append("&radius="+type);
                sb.append("&types=bus_station");
                sb.append("&sensor=true");
                sb.append("&key=APIKEY");

                // Creating a new non-ui thread task to download json data
                PlacesTask placesTask = new PlacesTask();

                // Invokes the "doInBackground()" method of the class
                placesTask.execute(sb.toString());

            }

        });

    }

    return view;
}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new 

        InputStreamReader(iStream));

        StringBuffer sb  = new StringBuffer();

        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }

    return data;
}

/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result){
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google places in JSON format
        // Invokes the "doInBackground()" method of the class ParseTask
        parserTask.execute(result);
    }

}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer,
List<HashMap<String,String>>>{

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String,String>> doInBackground(String...jsonData)

       {

        List<HashMap<String, String>> places = null;
        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

        try{
            jObject = new JSONObject(jsonData[0]);

            /** Getting the parsed data as a List construct */
            places = placeJsonParser.parse(jObject);

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String,String>> list){

        // Clears all the existing markers
        mGoogleMap.clear();

        for(int i=0;i<list.size();i++){

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            HashMap<String, String> hmPlace = list.get(i);

            // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("place_name");

            // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);

           // LatLng getmarker = markerOptions.getPosition();


            // Setting the title for the marker.
            //This will be displayed on taping the marker
            markerOptions.title(name + " : " + vicinity);

            // Placing a marker on the touched position
            mGoogleMap.addMarker(markerOptions);
        }
    }
}

@Override
public void onLocationChanged(Location location) {
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
    LatLng latLng = new LatLng(mLatitude, mLongitude);

    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(16));
   }

  public void setResult(int i, Intent returnIntent) {
    // TODO Auto-generated method stub

   }

  @Override
   public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
   }

  @Override
   public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
   }

  @Override
   public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
   }
 }

second.xml第二个.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"
android:orientation="vertical">

<Spinner
    android:id="@+id/spr_place_type"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_alignParentTop="true" />

<Spinner
    android:id="@+id/spr_radius"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_toRightOf="@id/spr_place_type"
    android:layout_alignParentTop="true" />

<Button
    android:id="@+id/btn_find"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@id/spr_radius"
    android:text="@string/str_btn_find" />

<fragment 
    android:id="@+id/map"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/spr_place_type"
    class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

Tabadapter翼龙

public class Tabsadapter extends FragmentStatePagerAdapter{

private int TOTAL_TABS = 3;

public Tabsadapter(FragmentManager fm) {
   super(fm);
   // TODO Auto-generated constructor stub
 }

@Override
public Fragment getItem(int index) {
   // TODO Auto-generated method stub
    switch (index) {
       case 0:
           return new RouteFragmentTab();

       case 1:
           return new FindRouteFragmentTab();

       case 2:
           return new MapRouteFragmentTab();
       }

       return null;
   }

  @Override
  public int getCount() {
   // TODO Auto-generated method stub
   return TOTAL_TABS;
    }
 }

You can use the replace() method on your fragment to replace the current fragment with another.您可以在片段上使用replace()方法将当前片段替换为另一个片段。

ie: replace(YourNewFragment.newInstance());即: replace(YourNewFragment.newInstance());

OR或者

If you don't want to actually replace the fragment, you can change tabs programmatically to the tab you want to display.如果您不想实际替换片段,则可以通过编程方式将选项卡更改为要显示的选项卡。 If you are using a ViewPager this can be done by calling yourViewPager.setCurrentItem(indexToSet) .如果您使用的是ViewPager这可以通过调用yourViewPager.setCurrentItem(indexToSet)来完成。

Let me know if this helps, or if you have any other questions in regard to my answer!如果这有帮助,或者您对我的回答有任何其他问题,请告诉我!

I was facing the same issue and i easily solved it by calling viewpager from the firstFragment class, and then easily setting the viewpager's current item to the index of the tab you want.我遇到了同样的问题,我通过从 firstFragment 类调用 viewpager 轻松解决了它,然后轻松地将 viewpager 的当前项目设置为您想要的选项卡的索引。

here's the code which i placed in the onClick method of the first tab fragment for me to go the third tab fragment;这是我放置在第一个选项卡片段的 onClick 方法中的代码,以便我转到第三个选项卡片段;

ViewPager viewPager = getActivity().findViewById(R.id.simpleViewPager);
viewPager.setCurrentItem(2);

My answer might be late, but i hope it helps anyone else who might meet this challenge.我的回答可能晚了,但我希望它可以帮助任何可能迎接这一挑战的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM