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

问题描述 投票:1回答:2

我有3个扩展程度片段的标签。第二个片段(扩展片段实现了locationListener)有一个带有公交车站标记的地图(完美工作)。我想从第一个选项卡通过一个按钮打开第二个片段,以获取marker(latlng)的位置。我的问题是我不能故意(startActivityforresult)这样做,因为它不是活动。您能否请任何人帮助我解决这个问题?

firstfragment.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 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 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;
    }
 }
java android android-fragments
2个回答
2
投票
即:replace(YourNewFragment.newInstance());

如果您不想实际

替换片段,则可以通过编程方式将选项卡更改为要显示的选项卡。如果您使用的是ViewPager,则可以通过调用yourViewPager.setCurrentItem(indexToSet)来完成。

让我知道这是否有帮助,或者您是否对我的回答还有其他疑问!


0
投票
这是我放置在第一个选项卡片段的onClick方法中的代码,可让我进入第三个选项卡片段;

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

我的回答可能晚了,但我希望它对其他可能遇到此挑战的人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.