将数据从片段返回到活动

时间:2018-07-23 11:56:41

标签: android android-fragments android-activity

在我的申请中,我有textView。当我单击它时,将显示一个片段,该片段包含一个autoCompleteTextView搜索的googleApi地址和一个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();
            }
        });

    }

}

2 个答案:

答案 0 :(得分:1)

假设该片段属于一个名为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);
}

答案 1 :(得分:-1)

创建界面

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As New HTMLDocument, i As Long, hNodeList As Object, pNodeList As Object

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://tuhoconline.net/tu-vung-n2-sach-mimi-kara-oboeru-4.html", False
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With

    sResponse = Mid$(sResponse, InStr(1, sResponse, "<!DOCTYPE "))

    With html
       .body.innerHTML = sResponse
      Set hNodeList = .querySelectorAll(".article-content h4")
      Set pNodeList = .querySelectorAll(".article-content h4 + h5 + p")

      For i = 0 To hNodeList.Length - 1
          Debug.Print hNodeList.item(i).innerText
          Debug.Print pNodeList.item(i).innerText
      Next i
    End With
End Sub

在您的 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(""); 中实施ISomeAction

activity