将数据从片段返回到活动



在我的应用程序中,我有textView。当我点击它时,会出现一个片段,该片段包含搜索googleApi地址的autoCompleteTextView和一个包含历史位置列表的recycleView。

我的问题是,当我点击其中一个地址(来自autoCompleteTextView或recycleView(时,我想返回所选地址,并在调用方活动中更新textView。

以下是自定义片段的代码:

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.widget.AutoSizeableTextView;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import com.facebook.places.model.PlaceInfoRequestParams;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.moneytime.busy.R;
import com.moneytime.busy.activities.ChooseAddressActivity;
import com.moneytime.busy.adapters.PlaceArrayAdapter;
import com.moneytime.busy.adapters.PlaceAutoCompleteAdapter;
import com.moneytime.busy.application.Analytics;
import com.moneytime.busy.application.CustomApplication;
import com.moneytime.busy.base.BaseActivity;
import com.moneytime.busy.base.BaseFragment;
import com.moneytime.busy.custom.CustomCompleteTextView;
import com.moneytime.busy.custom.ErrorDescriptor;
import com.moneytime.busy.network.NetworkManager;
import com.moneytime.busy.network.interfaces.MissionsNetworkResponseListener;
import com.moneytime.busy.network.requests.LastMissionsRequest;
import com.moneytime.busy.network.response.Location;
import com.moneytime.busy.network.response.Mission;
import com.moneytime.busy.adapters.UserLocationsAdapter;
import com.moneytime.busy.utils.LocationUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class LocationsFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener{
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}

private AutoCompleteTextView mCompleteTextView;
private ImageView closeBtn;
private RecyclerView rvLocationList;
private UserLocationsAdapter locationsHisAdapter;
private ArrayList<Location> locationsDataList;
private PlaceAutoCompleteAdapter aComLocationsAdapter;
private GoogleApiClient mGoogleApiClient;
//   private OnItemSelectedListener listener;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(new LatLng(-40, -168), new LatLng(71, 136));
public static final String EXTRA_LOCATION = "LOCATION_EXTRA";

public static LocationsFragment getInstance(LatLng mLastKnownLocation) {
LocationsFragment fragment = new LocationsFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_LOCATION, mLastKnownLocation);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_loctions_user, container, false);

initUiViews(v);
initUIFunctionality();
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
rvLocationList.addItemDecoration(itemDecoration);
getLocationsHistory();
return v;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onPause() {
super.onPause();
mGoogleApiClient.stopAutoManage(getActivity());
mGoogleApiClient.disconnect();
}

private void initUiViews(final View v) {
mCompleteTextView = (AutoCompleteTextView) v.findViewById(R.id.aCompleteTextView);
closeBtn=(ImageView)v.findViewById(R.id.closebtn) ;
rvLocationList = (RecyclerView) v.findViewById(R.id.locations_recyclerView);
rvLocationList.setLayoutManager(new LinearLayoutManager((getActivity())));
}
private void initUIFunctionality() {
closeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCompleteTextView.setText("");
}
});
mGoogleApiClient = new GoogleApiClient
.Builder(getContext())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(), this)
.build();
aComLocationsAdapter = new PlaceAutoCompleteAdapter(getContext(), mGoogleApiClient, LAT_LNG_BOUNDS, null);
mCompleteTextView.setAdapter(aComLocationsAdapter);
}
//Check duplicates items in list of address
public boolean contains(ArrayList<Location> list, String location) {
if (list.size() == 0)
return false;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getAddress().equals(location))
return true;
}
return false;
}
//Return List of History of address for the recycleView
public void getLocationsHistory() {
NetworkManager.getInstance().getCompletedOrders(new LastMissionsRequest(0), new MissionsNetworkResponseListener() {
@Override
public void onNetworkError(String errorMessage, int errorCode) {
if (errorCode == 999) {
((BaseActivity) getActivity()).showNoInternetDialog();
} else {
((BaseActivity) getActivity()).showNoInternetDialog();
}
}
@Override
public void onNetworkSuccess(List<Mission> missionList) {
locationsDataList = new ArrayList<>();
int count = 0;
for (Mission mission : missionList) {
if (count < 5) {
if (!contains(locationsDataList, mission.getDeliveryLocation().getAddress())) {
locationsDataList.add(mission.getDeliveryLocation());
count++;
}
}
}
locationsHisAdapter = new UserLocationsAdapter(getActivity(), locationsDataList);
rvLocationList.setAdapter(locationsHisAdapter);
//locationsHisAdapter.notifyDataSetChanged();
}
});
}
}

假设片段属于一个名为MainActivity的活动(否则只需更改示例中的名称(:

在MainActivity.class:上

public void updateWhateverYouWantOnMainActivity(String whateverAddress){
//update activity stuff here
}

在您的片段上:

((MainActivity) getActivity()).updateWhateverYouWantOnMainActivity(yourSelectedAddress);

编辑:

您还可以创建一个接口:

public interface OnAddressChangedListener{
onAddressChanged(String newAddress);
}

然后,在创建片段时,vou可以将调用方活动作为接口实现传入:

在您的活动中,创建片段时:

Fragment fragment = new MyFragment();
fragment.setOnAddressChangedListener(new OnAddressChangedListener(){
@Override
public void onAddressChanged(String newAddress){
//update activity stuff here
}
});

你的碎片:

public void setOnAddressChangedListener(OnAddressChangedListener listener){
this.listener = listener;
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
this.listener.onAddressChanged(yourSelectedAddress);
}

创建接口

interface ISomeAction extends Serializable{
void sendAddress(String address);
}

在您的LocationsFragment

private ISomeAction iSomeAction;
public static LocationsFragment getInstance(LatLng mLastKnownLocation,ISomeAction iSomeAction) {
args.putSerializable("interface", iSomeAction);
//other code
}

onCreateView

Bundle bundle = getArguments();
iSomeAction = (ISomeAction) bundle.getSerializable("interface");

点击或其他操作

iSomeAction.sendAddress("");

activity中实现ISomeAction

@Override
public void sendAddress(String address) {
//Your action such as settext to textview
}

最新更新