简体   繁体   中英

Add clicked item of a List view of a fragment to a List View of another fragment

Iam working on an Android application.I have two fragment in a Tab layout both of the fragments have list views with custom adapters.Fragment one loads a list and I want to add selected item of listview of Fragment 1 to the listview of fragment 2. Fragment one code and and my adapter looks like this.

public class TestFragment2 extends Fragment{
    TextView textView;
    public ListView listView;
    String text;
    static YukilanAdapter yukilanAdapter;
    private static List<YukilanModel> list = new ArrayList<YukilanModel>();
    static OkHttpClient client;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        yukilanAdapter=new YukilanAdapter(list,getContext());

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_test2, container, false);



        GetTask getTask=new GetTask();
        getTask.execute();


        listView=(ListView)rootView.findViewById(R.id.yukilanliste_view);
        listView.setAdapter(yukilanAdapter);



            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                }
            });

        return rootView;
    }

    static class GetTask extends AsyncTask<String, Void, String> {
        List<YukilanModel> gelenveri;
        private Exception exception;

        protected String doInBackground(String... urls) {

            try {

                ClientOlustur();


                String getResponse = get("url");
                return getResponse;
            } catch (Exception e) {
                this.exception = e;
                return null;
            }
        }

        protected void onPostExecute(String getResponse) {

            try {

                    Log.d("TEST FRAGMENT2","EXECUTED");
                JSONObject jsonObject = new JSONObject(getResponse);
                JSONArray yukilanarray = jsonObject.getJSONArray("result");
                gelenveri = new ArrayList<>();

                for (int i = 0; i < yukilanarray.length(); i++) {
                    YukilanModel yeniilan = new YukilanModel();
                    JSONObject yukilanobject = yukilanarray.getJSONObject(i);
                    yeniilan.setSehir(yukilanobject.getString("a_sehir"));
                    yeniilan.setHedefsehir(yukilanobject.getString("hedef_sehir"));
                    yeniilan.setYukcins(yukilanobject.getString("yukcins"));
                    yeniilan.setAgirlik(yukilanobject.getString("agirlik"));
                    yeniilan.setArac(yukilanobject.getString("aractipi"));




                                /*    if (yukilanobject.getString("yukcins").equals("sebze"))
                                    {
                                        yeniilan.setResim(getContext().getResources().getDrawable(R.drawable.sebze));
                                    }*/

                    gelenveri.add(yeniilan);
                }

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

            list.clear();
            list.addAll(gelenveri);

            yukilanAdapter.notifyDataSetChanged();
            //  listView.setAdapter(tazele);

        }

        public String get(String url) throws IOException {
            Request request = new Request.Builder()
                    .url(url)
                    .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
        }

        public void ClientOlustur() {
            client = new OkHttpClient.Builder()
                    .authenticator(new Nakliyeauthenticator())
                    .build();
        }

        class Nakliyeauthenticator implements Authenticator {
            //gets called if server responds with 401 http response to retry authentication
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                String credential = Credentials.basic("user", "password");

                //prevent infinite loop , if same credentials already tired, no need to try again
                if (credential.equals(response.request().header("Authorization"))) {
                    return null;
                }

                return response.request().newBuilder()
                        .header("Authorization", credential)
                        .build();
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }

}

My adapter looks like this

public class YukilanAdapter extends ArrayAdapter<YukilanModel> {
    private static final String KEY_ADRES="Şehir: ";
    private static final String KEY_TAKIPKODU="Takipkodu: ";
    private static final String KEY_AGIRLIK="Ağırlık: ";
    private static final String KEY_YUKCINS="Yukcins: ";
            OkHttpClient client;
            String gelennumara;




    private List<YukilanModel> veriliste;

    public YukilanAdapter(List<YukilanModel> veriliste, Context mContext) {
        super(mContext, R.layout.ilanitem,veriliste);
        this.veriliste = veriliste;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View v = convertView;
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.ilanitem,null);
        }
        YukilanModel yukilan = veriliste.get(position);
        if (yukilan != null) {

           TextView a_adresview = (TextView) v.findViewById(R.id.sehir1);
            TextView hedef_adres_view = (TextView) v.findViewById(R.id.sehir2);
           TextView agirlikview = (TextView) v.findViewById(R.id.yuk);
            TextView arac_view=(TextView) v.findViewById(R.id.arac);
            View cizgi1=(View)v.findViewById(R.id.cizgi1);
            View cizgi2=(View)v.findViewById(R.id.cizgi2);


            a_adresview.setText(yukilan.getSehir());
            hedef_adres_view.setText(yukilan.getHedefsehir());
            agirlikview.setText(yukilan.getAgirlik());
            arac_view.setText(yukilan.getArac());

                if((arac_view.getText().toString()).equals("tır"))
                {
                    cizgi1.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.mavi));
                }else
                {
                    cizgi1.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.kirmizi));
                }

        }

        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String cins=getItem(position).getYukcins();
                String sehir=getItem(position).getSehir();
                String hedef=getItem(position).getHedefsehir();
                String agirlik=getItem(position).getAgirlik();
            Bundle bundle=new Bundle();
                            Intent newintent=new Intent(getContext(),Ilandetay.class);
                                        bundle.putString("YUKCINS",cins);
                                        bundle.putString("SEHIR",sehir);
                                        bundle.putString("HEDEF",hedef);
                                        bundle.putString("AGIRLIK",agirlik);

                                        newintent.putExtras(bundle);

                getContext().startActivity(newintent);



               // Log.d("ON CLICK TEST",agirlik);
            }
        });

        return v;
    }

}

Make a custom callback interface. Call this from one listview of one fragment and pass the selected value in the call back.

Now implement it in the other fragment to recieve that value.

Then call adapter.notifydatasetchanged() function to notify the data set change.

Further you can visit this link :

How to pass values between Fragments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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