我有3个标签片段。第二个片段(extends fragment implements locationListener)有一个带有公交车站标记的地图(工作完美)。我希望从第一个标签通过一个按钮打开第二个片段以获得标记(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;
}
}
答案 0 :(得分:0)
您可以在片段上使用replace()
方法将当前片段替换为另一个片段。
即:replace(YourNewFragment.newInstance());
OR
如果您不想实际替换片段,可以通过编程方式将标签更改为要显示的标签。如果您使用的是ViewPager
,可以致电yourViewPager.setCurrentItem(indexToSet)
。
如果这有帮助,或者如果您对我的回答有任何其他问题,请告诉我们!
答案 1 :(得分:0)
我也遇到了同样的问题,我可以通过从firstFragment类调用viewpager,然后轻松地将viewpager的当前项设置为所需标签的索引来轻松解决此问题。
这是我放置在第一个选项卡片段的onClick方法中的代码,以便我进入第三个选项卡片段;
ViewPager viewPager = getActivity().findViewById(R.id.simpleViewPager);
viewPager.setCurrentItem(2);
我的回答可能太迟了,但我希望它对可能遇到此挑战的其他人有所帮助。