android - 如何将值从 ListView 适配器传递到 fragment ?

标签 android listview android-fragments android-listview listview-adapter

请帮帮我..

我想将值从我的 listviewadapter 项目传递到我的 fragment ..

我有ListViewAdapterShipping.java

    package com.example.administrator.mosbeau;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

/**
 * Created by Administrator on 11/9/2015.
 */
public class ListViewAdapterShipping extends BaseAdapter {

    boolean expanded = false;

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapterShipping(Context context,
                           ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
    }

    String mconfiguration_id;

    private RadioButton mSelectedRB;
    private int mSelectedPosition = -1;

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }


    public interface AdapterInterface
    {
        void onClick(String value);
    }

    AdapterInterface listener;
    public ListViewAdapterShipping(AdapterInterface listener)
    {
        this.listener = listener;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView configuration_id;
        RadioButton shipping_title;
        TextView shipping_weight;
        ImageView shipping_icon;
        TextView shipping_price;
        TextView shipping_desc;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.shippingrate_item, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in product_gridview_item.xml

        configuration_id = (TextView) itemView.findViewById(R.id.textconfigurationid);
        shipping_title = (RadioButton) itemView.findViewById(R.id.radioShippingtitle);
        shipping_weight = (TextView) itemView.findViewById(R.id.textWeight);
        shipping_icon = (ImageView) itemView.findViewById(R.id.shipping_icon);
        shipping_price = (TextView) itemView.findViewById(R.id.textPrice);
        shipping_desc = (TextView) itemView.findViewById(R.id.textDesc);

        // Capture position and set results to the TextViews
        configuration_id.setText(resultp.get(CheckoutFragment1.configuration_id));
        shipping_title.setText(resultp.get(CheckoutFragment1.shipping_title));
        shipping_weight.setText(resultp.get(CheckoutFragment1.shipping_weight));
        shipping_price.setText(resultp.get(CheckoutFragment1.shipping_price));
        shipping_desc.setText(resultp.get(CheckoutFragment1.shipping_desc));
        // Capture position and set results to the ImageView
        Glide.with(context).load(resultp.get(CheckoutFragment1.shipping_icon)).diskCacheStrategy(DiskCacheStrategy.ALL).into(shipping_icon);
        int color = 0xffffffff;
        itemView.setBackgroundColor(color);

        mconfiguration_id = configuration_id.getText().toString();
        shipping_title.setTag(mconfiguration_id);
        shipping_title.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (position != mSelectedPosition && mSelectedRB != null) {
                    mSelectedRB.setChecked(false);
                }

                mSelectedPosition = position;
                mSelectedRB = (RadioButton) v;

                String mconfiguration_id;
                mconfiguration_id = v.getTag().toString();
                //Toast.makeText(context, mconfiguration_id, Toast.LENGTH_SHORT).show();
                if(listener != null)
                    listener.onClick(mconfiguration_id);
            }

        });

        if(mSelectedPosition != position){
            shipping_title.setChecked(false);
        }else{
            shipping_title.setChecked(true);
            if(mSelectedRB != null && shipping_title != mSelectedRB){
                mSelectedRB = shipping_title;
            }
        }

        return itemView;
    }
}

这是我的CheckoutFragment1.java

    package com.example.administrator.mosbeau;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 11/7/2015.
 */
public class CheckoutFragment1 extends Fragment implements View.OnClickListener {

    public static CheckoutFragment1 newInstance(String customersid, String countryid, String weightotal, String subtotal, String stateid) {
        CheckoutFragment1 fragment = new CheckoutFragment1();

        Bundle bundle = new Bundle();
        bundle.putString("customersid", customersid);
        bundle.putString("countryid", countryid);
        bundle.putString("weightotal", weightotal);
        bundle.putString("subtotal", subtotal);
        bundle.putString("stateid", stateid);
        fragment.setArguments(bundle);

        return fragment;
    }

    public CheckoutFragment1 () {
    }

    String customersid, countryid, weightotal, subtotal, stateid;

    public static final int CONNECTION_TIMEOUT = 1000 * 15;
    public static final String SERVER_ADDRESS = "http://shop.mosbeau.com.ph/android/";

    String myJSONShippingRate, myJSONShippingInfo;
    JSONArray jsonarrayShippingRate, jsonarrayShippingInfo;

    ExpandableHeightListView shippingratelistview;
    ListViewAdapterShipping shippingrateadapter;

    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> shippingratearraylist;
    public static String configuration_id = "configuration_id";
    public static String shipping_title = "shipping_title";
    public static String shipping_weight = "shipping_weight";
    public static String shipping_icon = "shipping_icon";
    public static String shipping_price = "shipping_price";
    public static String shipping_desc = "shipping_desc";

    TextView textCompany, textName, textStreet, textCity, textState, textZip, textCountry, textShippingRateId;
    Button btnContinue;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.checkoutlayout1, container, false);

        ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
        //boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
        if(isConnected){
            getShippingRate();
            getShippingInfo();
        }else{
            nointernet();
        }

        if(getArguments() != null) {
            String ccustomersid = getArguments().getString("customersid");
            String ccountryid = getArguments().getString("countryid");
            String cweightotal = getArguments().getString("weightotal");
            String csubtotal = getArguments().getString("subtotal");
            String cstateid = getArguments().getString("stateid");

            customersid = ccustomersid;
            countryid = ccountryid;
            weightotal = cweightotal;
            subtotal = csubtotal;
            stateid = cstateid;
        }

        shippingratelistview = new ExpandableHeightListView(getActivity());
        shippingratelistview = (ExpandableHeightListView) rootView.findViewById(R.id.shippinglist);

        textCompany = (TextView) rootView.findViewById(R.id.textCompany);
        textName = (TextView) rootView.findViewById(R.id.textName);
        textStreet = (TextView) rootView.findViewById(R.id.textStreet);
        textCity = (TextView) rootView.findViewById(R.id.textCity);
        textState = (TextView) rootView.findViewById(R.id.textState);
        textZip = (TextView) rootView.findViewById(R.id.textZip);
        textCountry = (TextView) rootView.findViewById(R.id.textCountry);
        textShippingRateId = (TextView) rootView.findViewById(R.id.textShippingRateId);

        btnContinue = (Button) rootView.findViewById(R.id.btnContinue);
        btnContinue.setOnClickListener(this);

        showGlobalContextActionBar();

        return rootView;
    }

    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle("SHIPPING");
    }

    private ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }

    public void getShippingRate(){
        class DownloadJSONShippingRate extends AsyncTask<String, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                /*mProgressDialog = new ProgressDialog(getActivity());
                // Set progressdialog title
                //mProgressDialog.setTitle(cname);
                // Set progressdialog message
                mProgressDialog.setMessage("Please wait...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();*/
                mProgressDialog = ProgressDialog.show(getActivity(), null, null, true, false);
                mProgressDialog.setContentView(R.layout.progressdialog);
            }

            @Override
            protected String doInBackground(String... params) {
                ArrayList<NameValuePair> dataToSend = new ArrayList<>();
                dataToSend.add(new BasicNameValuePair("customersid", customersid));
                dataToSend.add(new BasicNameValuePair("countryid", countryid));
                dataToSend.add(new BasicNameValuePair("stateid", stateid));
                dataToSend.add(new BasicNameValuePair("weightotal", weightotal));
                dataToSend.add(new BasicNameValuePair("subtotal", subtotal));

                HttpParams httpRequestParams = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost(SERVER_ADDRESS + "shippingrate.php");

                // Depends on your web service
                //httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String shippingrateresult = null;
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(dataToSend));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    shippingrateresult = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return shippingrateresult;
            }

            @Override
            protected void onPostExecute(String shippingrateresult){
                myJSONShippingRate=shippingrateresult;

                try {
                    // Locate the array name in JSON
                    JSONObject jsonObjcart = new JSONObject(myJSONShippingRate);
                    jsonarrayShippingRate = jsonObjcart.getJSONArray("shippingrate");
                    shippingratearraylist = new ArrayList<HashMap<String, String>>();
                    int qtySum = 0, qtyNum, tqtySum;
                    for (int i = 0; i < jsonarrayShippingRate.length(); i++) {
                        HashMap<String, String> lmap = new HashMap<String, String>();
                        JSONObject p = jsonarrayShippingRate.getJSONObject(i);
                        // Retrive JSON Objects
                        lmap.put("configuration_id", p.getString("configuration_id"));
                        lmap.put("shipping_title", p.getString("shipping_title"));
                        lmap.put("shipping_weight", p.getString("shipping_weight"));
                        lmap.put("shipping_desc", p.getString("shipping_desc"));
                        lmap.put("shipping_icon", p.getString("shipping_icon"));
                        lmap.put("shipping_price", p.getString("shipping_price"));

                        shippingratearraylist.add(lmap);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }

                shippingrateadapter = new ListViewAdapterShipping(getActivity(), shippingratearraylist);
                shippingratelistview.setAdapter(shippingrateadapter);
                shippingratelistview.setExpanded(true);

                ListViewAdapterShipping.AdapterInterface listener = (new ListViewAdapterShipping.AdapterInterface() {
                    public void onClick(String value)
                    {
                        textShippingRateId.setText("000");
                    }
                });

                ListViewAdapterShipping adapter = new ListViewAdapterShipping(listener);

                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
        DownloadJSONShippingRate g = new DownloadJSONShippingRate();
        g.execute();
    }

    public void getShippingInfo(){
        class DownloadJSONShippingInfo extends AsyncTask<String, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                /*mProgressDialog = new ProgressDialog(getActivity());
                // Set progressdialog title
                //mProgressDialog.setTitle(cname);
                // Set progressdialog message
                mProgressDialog.setMessage("Please wait...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();*/
                /*mProgressDialog = ProgressDialog.show(getActivity(), null, null, true, false);
                mProgressDialog.setContentView(R.layout.progressdialog);*/
            }

            @Override
            protected String doInBackground(String... params) {
                ArrayList<NameValuePair> dataToSend = new ArrayList<>();
                dataToSend.add(new BasicNameValuePair("customersid", customersid));

                HttpParams httpRequestParams = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost(SERVER_ADDRESS + "shippinginfo.php");

                // Depends on your web service
                //httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String shippinginforesult = null;
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(dataToSend));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    shippinginforesult = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return shippinginforesult;
            }

            @Override
            protected void onPostExecute(String shippinginforesult){
                myJSONShippingInfo=shippinginforesult;

                try {
                    // Locate the array name in JSON
                    JSONObject jsonObjcart = new JSONObject(myJSONShippingInfo);
                    jsonarrayShippingInfo = jsonObjcart.getJSONArray("shippinguserinfo");
                    for (int i = 0; i < jsonarrayShippingInfo.length(); i++) {
                        JSONObject sp = jsonarrayShippingInfo.getJSONObject(i);
                        textCompany.setText(sp.getString("entry_company"));
                        textName.setText(sp.getString("customers_firstname") + ' ' + sp.getString("customers_lastname"));
                        textStreet.setText(sp.getString("entry_street_address"));
                        textCity.setText(sp.getString("entry_city"));
                        textState.setText(sp.getString("entry_state"));
                        textZip.setText(sp.getString("zone_name"));
                        textCountry.setText(sp.getString("countries_name"));
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                // Close the progressdialog
                /*mProgressDialog.dismiss();*/
            }
        }
        DownloadJSONShippingInfo g = new DownloadJSONShippingInfo();
        g.execute();
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.btnContinue:
                CheckoutFragment2 checkoutfragment2 = CheckoutFragment2.newInstance();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, checkoutfragment2)
                        .addToBackStack(null)
                        .commit();
                break;
        }
    }



    public void nointernet(){
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        dialogBuilder.setMessage("There seems to be a problem with your connection.");
        dialogBuilder.setNegativeButton("Edit Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Stop the activity
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            }

        });
        dialogBuilder.setPositiveButton("Reload", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Stop the activity
                HomeFragment homefragment = HomeFragment.newInstance();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, homefragment)
                        .addToBackStack(null)
                        .commit();
            }

        });
        AlertDialog dialog = dialogBuilder.show();
        TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
        messageText.setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }
}

好的,我想要的是将 mconfiguration_id 的值从我的适配器传递到我的 fragment 并分配给变量..

谢谢

最佳答案

您必须在适配器类中创建接口(interface)。

public interface AdapterInterface
{
   void onClick(String value);
}

然后在您的适配器构造函数中添加一个参数作为

AdapterInterface listener;
public AdapterName(AdapterInterface listener)
{
   this.listener = listener;
}

现在在适配器中,当你想要像按钮点击一样改变时

shipping_title.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (position != mSelectedPosition && mSelectedRB != null) {
                    mSelectedRB.setChecked(false);
                }

                mSelectedPosition = position;
                mSelectedRB = (RadioButton) v;

                String mconfiguration_id;
                mconfiguration_id = v.getTag().toString();
                //Toast.makeText(context, mconfiguration_id, Toast.LENGTH_SHORT).show();
                if(listener != null)
                    listener.onClick(mconfiguration_id);
            }

        });

在你初始化适配器的 fragment 中

AdapterInterface listener = new AdapterInterface()
{
  public void onClick(String value)
  {
    //whatever you want to do.
    //you will get call back here
  }
}

AdapterName adapter = new AdapterName(listener);

编辑:

更改如下。

AdapterInterface listener = new AdapterInterface() 
{
     @Override
     public void onClick(String value)
     {
        textShippingRateId.setText("000");
     }
};
shippingrateadapter = new ListViewAdapterShipping(getActivity(), shippingratearraylist, listener);
shippingratelistview.setAdapter(shippingrateadapter);

并在您的适配器的构造函数中根据它进行更改。

关于android - 如何将值从 ListView 适配器传递到 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33622130/

相关文章:

android - 方向更改后 fragment 中的叠加小部件

java - 为什么 R 无法识别我的 "about"标签

android - fragment 实例中带有 Otto 事件总线的 IllegalArgumentException

Android - 扩展 setOnGroupExpandListener 方法

java - 为什么 Wicket ListView 仅将更改分配给最后一行?

c# - 为什么这段代码在 Windows 7 上有效,但在 Windows XP 上却无效?

Android 在 PreferenceScreens 之间切换

java - AsyncTask 中的循环器

android - OnItemClickListener 和自定义 OnTouchListener

java - 滑动时的 Android ViewPager Bug