onItemClickListener between two fragments

本秂侑毒 提交于 2019-12-02 01:06:35

问题


I am very new with android.I have tried but not able to find out what i am missing. I am using two fragments two display the list. Now i want to change the list data in second fragment when user click on the first list item. By default zero position index will be selected to display the data in second list. I am using custom array adapter to display the list in both fragments.Please help me out guys.Thanks for considering. Here i am pasting my code :

Activity Class:

   public class ProductListActivity extends Activity implements ProductInterface {
public static String cookie;
public static String jsonSettingsResponse;
public static String[] tids;
public static String jsonPorductsCategoryListResponseString;
public JSONArray jsonPorductsCategoryListResponseArray;
public static String vid;
public static String publicPath;
public static JSONArray productsList;
public ArrayList<String> listItems;
public String[] listProCategory;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.product_category_and_list);
    Intent intent = getIntent();
    cookie = intent.getStringExtra(BConstant.WEB_SERVICES_COOKIES);
    productsList = new JSONArray();

    FetchProductCategories products = new FetchProductCategories();
    productsList = products.fetchProducts();
    listProCategory = products.onDisplayProductList(productsList).toArray(
            new String[0]);

    Bundle bundle = new Bundle();
    bundle.putString(BConstant.WEB_SERVICES_COOKIES, cookie);
    bundle.putString(BConstant.PUBLIC_PATH, publicPath);
    bundle.putStringArray(BConstant.TAXONOMY_TID, tids);
    bundle.putStringArray(BConstant.PRODUCT_CATEGORY_NAMES,
            listProCategory);
    ProductCategoryFragment.newInstance(bundle);
    Bundle bundleForProductList = new Bundle();
    bundleForProductList.putStringArray(BConstant.TAXONOMY_TID, tids);
    bundleForProductList.putString(BConstant.WEB_SERVICES_COOKIES, cookie);
    ProductListFragment.newInstance(bundleForProductList);
}


private class FetchProductCategories {
    protected JSONArray fetchProducts(String... params) {
        jsonSettingsResponse = WebserviceBUtil
                .callWebServicesGetVocabularyList(cookie);
        vid = JSONUtil.parseJSONResponse(jsonSettingsResponse,
                BConstant.TAXONOMY_VID);
        publicPath = JSONUtil.parseJSONResponse(jsonSettingsResponse,
                BConstant.PUBLIC_PATH);
        jsonPorductsCategoryListResponseString = WebserviceBUtil
                .callWebServicesGetProductsCategoryList(cookie, vid);
        tids = ProductCategoryIds.parseJSONResponseToGetTidsOfProducts(
                jsonPorductsCategoryListResponseString,
                BConstant.TAXONOMY_TID);
        try {
            jsonPorductsCategoryListResponseArray = new JSONArray(
                    jsonPorductsCategoryListResponseString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonPorductsCategoryListResponseArray;
    }


    protected ArrayList<String> onDisplayProductList(JSONArray result) {
        listItems = new ArrayList<String>();
        for (int i = 0; i < result.length(); i++) {
            try {
                listItems
                        .add(result.getJSONObject(i)
                                .getString(BConstant.NAME_CONSTANT)
                                .toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return listItems;
    }
}


@Override
public HashMap<Integer, Bitmap> DownloadImages(
        HashMap<Integer, String> productCategoryImagePath) {
    HashMap<Integer, Bitmap> imgBitmap = new HashMap<Integer, Bitmap>();
    for (int pos = 0; pos < productCategoryImagePath.size(); pos++) {
        Bitmap bval = ImageDownloader
                .getBitmapFromURL(productCategoryImagePath.get(pos));
        imgBitmap.put(pos, bval);
    }
    return imgBitmap;

}

@Override
public void clickedProductCategory(String tid) {
    FragmentManager productListFragmentManager = getFragmentManager();
    ProductListFragment productListFragment = (ProductListFragment) productListFragmentManager
            .findFragmentById(R.id.proListfragment);
    productListFragment.clickedProductCategoryIdByProductCategoryFragment(tid);

}

}

First Fragment:

    public class ProductCategoryFragment extends Fragment implements OnItemClickListener{
ProductInterface productInterface;
private static String[] tids;
private static HashMap<Integer, String> productCategoryImagePath;
private static String jsonPorductsDetailsImagePathResponse;
private static String publicPath;
private static String cookie;
public static String[] listProCategory;
public  ListView listOfProductsCategory;
private static HashMap<Integer, Bitmap> imgBitmapUrls;
DisplayProductCategoryListArrayAdapter adapter;


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

listOfProductsCategory =(ListView) fragProcatView .findViewById(R.id.productCategorylistView);
    return fragProcatView;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    productInterface = (ProductInterface) getActivity();
    productCategoryImagePath = new HashMap<Integer, String>();
    for (int i = 0; i < tids.length; i++) {
        jsonPorductsDetailsImagePathResponse = WebserviceBUtil
                .callWebServicesGetProductsDetails(cookie, tids[i]);
        String filename = ProductCategoryIds
                .parseJSONResponseToGetVidOfProductsFromVocabulary(
                        jsonPorductsDetailsImagePathResponse,
                        BConstant.FILE_NAME);
        String completeUrl = publicPath + filename;
        productCategoryImagePath.put(i, completeUrl);
    }
    imgBitmapUrls = productInterface
            .DownloadImages(productCategoryImagePath);
     adapter = new DisplayProductCategoryListArrayAdapter(
                getActivity(), listProCategory,
                imgBitmapUrls);
    listOfProductsCategory.setAdapter(adapter);
    listOfProductsCategory.setOnItemClickListener(this);
}
 static ProductCategoryFragment newInstance(Bundle bundle) {
        ProductCategoryFragment productCategoryFragment = new ProductCategoryFragment();
        productCategoryFragment.setArguments(bundle);
        cookie = bundle.getString(BConstant.WEB_SERVICES_COOKIES);
        tids = bundle.getStringArray(BConstant.TAXONOMY_TID);
        publicPath = bundle.getString(BConstant.PUBLIC_PATH);
listProCategory = bundle.getStringArray(BConstant.PRODUCT_CATEGORY_NAMES);
        return productCategoryFragment;
    }

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    String clickedItemName = (String) listOfProductsCategory
            .getItemAtPosition(position);
    int clickedItemId = (int) listOfProductsCategory
            .getItemIdAtPosition(position);

    Toast.makeText(this.getActivity(),
            "Product is getting load : " + clickedItemName,
            Toast.LENGTH_SHORT).show();
        productInterface.clickedProductCategory(tids[clickedItemId]);
}


public class DisplayProductCategoryListArrayAdapter extends ArrayAdapter<String> {

    Context context;
    HashMap<Integer, Bitmap> prodctImgs;
    String[] proCategoryNames;
    HashMap<Integer, Bitmap>biturls;
    DisplayProductCategoryListArrayAdapter(Context c,
            String[] listCategory, HashMap<Integer, Bitmap> imgUrls) {
        super(c,
                R.layout.product_category_single_layout,
                R.id.productCategoryName, listCategory);
        this.context = c;
        this.prodctImgs = imgUrls;
        this.proCategoryNames = listCategory;
        this.biturls = imgUrls;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=((Activity)context).getLayoutInflater(); 
    View row = inflater.inflate(R.layout.product_category_single_layout, parent, false);
        ImageView productCategoryImage = (ImageView) row
                .findViewById(R.id.productCategoryImageId);
        Bitmap bitmap = imgBitmapUrls.get(position);
        // productCategoryImage.setFocusable(false);
        TextView productCategoryName = (TextView) row
                .findViewById(R.id.productCategoryName);
        productCategoryImage.setImageBitmap(bitmap);
        productCategoryName.setText(proCategoryNames[position]);
        return row;
    }
}
  }

Secoond Fragment:

    public class ProductListFragment extends Fragment implements OnItemClickListener{
private static HashMap<Integer, Bitmap> imgBitmapUrls;
public  ListView listOfProducts;
ProductInterface productInterfaceForProductList;
private static String jsonPorductsCategoryListResponse;
private static String cookie;
private static String[] productImgPath;
private static String[] nids;
private static String[] title;
private static String[] tids;
private String tid;
private static HashMap<Integer, String> productListImagePath;
DisplayProductListArrayAdapter proListAdapter;
@Override
 public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState ) {
     View fragProListView = inflater.inflate(R.layout.product_category_list, container,
                false);
     listOfProducts =(ListView) fragProListView .findViewById(R.id.productCategorylistView);
    return fragProListView;
    }

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    productInterfaceForProductList = (ProductInterface) getActivity();
    jsonPorductsCategoryListResponse = WebserviceBUtil.
            callWebServicesGetProductsList(cookie, tids[0]);
    nids = ProductCategoryIds.parseJSONResponseToGetTidsOfProducts(
            jsonPorductsCategoryListResponse,
            BConstant.PRODUCT_NODE_ID);
    title = ProductCategoryIds.parseJSONResponseToGetTidsOfProducts(
            jsonPorductsCategoryListResponse,
            BConstant.PRODUCT_TITLE);
    productImgPath = ProductCategoryIds.parseJSONResponseToGetTidsOfProducts(
            jsonPorductsCategoryListResponse,
            BConstant.PRODUCT_IMAGE);
            productListImagePath = new HashMap<Integer, String>();
            for(int i =0;i<productImgPath.length;i++){
                productListImagePath.put(i, productImgPath[i]);
            }
            System.out.println(productListImagePath);
    imgBitmapUrls = productInterfaceForProductList
            .DownloadImages(productListImagePath);

    proListAdapter = new DisplayProductListArrayAdapter(
                getActivity(), title,
                imgBitmapUrls);
     listOfProducts.setAdapter(proListAdapter);
     listOfProducts.setOnItemClickListener(this);
}
 static ProductListFragment newInstance(Bundle bundle) {
     ProductListFragment productListFragment = new ProductListFragment();
     productListFragment.setArguments(bundle);
        cookie = bundle.getString(BConstant.WEB_SERVICES_COOKIES);
        tids = bundle.getStringArray(BConstant.TAXONOMY_TID);
        return productListFragment;
    }
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

}



public class DisplayProductListArrayAdapter extends ArrayAdapter<String> {

    Context context;
    HashMap<Integer, Bitmap> prodctImgs;
    String[] proCategoryNames;
    HashMap<Integer, Bitmap>biturls;
    DisplayProductListArrayAdapter(Context c,
            String[] listCategory, HashMap<Integer, Bitmap> imgUrls) {
        super(c,
                R.layout.products_list_single_layout,
                R.id.productCategoryName, listCategory);
        this.context = c;
        this.prodctImgs = imgUrls;
        this.proCategoryNames = listCategory;
        this.biturls = imgUrls;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=((Activity)context).getLayoutInflater(); 
View row = inflater.inflate(R.layout.products_list_single_layout, parent, false);
        ImageView productCategoryImage = (ImageView) row
                .findViewById(R.id.productImageId);
        Bitmap bitmap = imgBitmapUrls.get(position);
        // productCategoryImage.setFocusable(false);
        TextView productCategoryName = (TextView) row
                .findViewById(R.id.productName);
        productCategoryImage.setImageBitmap(bitmap);
        productCategoryName.setText(proCategoryNames[position]);
        return row;
    }
}

public void clickedProductCategoryIdByProductCategoryFragment(String tid){
    jsonPorductsCategoryListResponse = WebserviceBUtil.
            callWebServicesGetProductsList(cookie, tid);

}
 }

回答1:


You can create interface that will be listener for and action from first fragment and passing action to your activity.

And in your Activity you can update data in second Fragment.

public interface IFoo
{
 public void foo();
}

in first Fragment

    IFoo responder; //global variable

    private ProductCategoryFragment(IFoo resp)
    {
    this.responder=resp;
    }

     static ProductCategoryFragment newInstance(Bundle bundle, IFoo resp) {
        ProductCategoryFragment productCategoryFragment = new ProductCategoryFragment(resp);
        productCategoryFragment.setArguments(bundle);
        cookie = bundle.getString(BsharpConstant.WEB_SERVICES_COOKIES);
        tids = bundle.getStringArray(BsharpConstant.TAXONOMY_TID);
        publicPath = bundle.getString(BsharpConstant.PUBLIC_PATH);
listProCategory = bundle.getStringArray(BsharpConstant.PRODUCT_CATEGORY_NAMES);
        return productCategoryFragment;
    }

and somewere in fragment

responder.foo();

in your Activity

public class ProductListActivity extends Activity implements IFoo
{
...
public void foo()
{
 //pass data to second fragment
}

onCreate
{
...
ProductCategoryFragment.newInstance(bundle, this);
}
}

Make your fragments global variable to have access them in every moment

I hope it is clear and would help. If is not clear, feel free to ask additional questions :)



来源:https://stackoverflow.com/questions/20683593/onitemclicklistener-between-two-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!