如何在baseview中使用baseadapter显示listview中的添加到购物车按钮

时间:2018-06-18 05:32:33

标签: android listview baseadapter

我正在开发一个电子商务应用程序,我有一个列表,其中的项目列表将在那里。就像从数据库中提取的产品名称,价格,折扣价值等一样。

我正在使用ListView来显示每个项目都有分隔 Menu_ID 的产品。每当我点击列表项目后,我会使用 putExtra 来打开speciefic menu_id 项目详细信息。

public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            // TODO Auto-generated method stub
            // go to menu detail page
            Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
            iDetail.putExtra("menu_id", Menu_ID.get(position));
            startActivity(iDetail);
        }

新的活动将打开产品详细信息,只要我点击购物车活动中的添加到购物车按钮项目,我就会显示添加到购物车按钮。

代码就像

public void inputDialog() {

    // open database first
    try {
        dbhelper.openDataBase();
    } catch (SQLException sqle) {
        throw sqle;
    }

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle(R.string.order);
    alert.setMessage(R.string.number_order);
    alert.setCancelable(false);
    final EditText edtQuantity = new EditText(this);
    int maxLength = 3;
    edtQuantity.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
    edtQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
    alert.setView(edtQuantity);

    alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String temp = edtQuantity.getText().toString();
            int quantity = 0;

            // when add button clicked add menu to order table in database
            if (!temp.equalsIgnoreCase("")) {
                quantity = Integer.parseInt(temp);
                Toast.makeText(getApplicationContext(), "Success add product to cart", Toast.LENGTH_SHORT).show();

                if (dbhelper.isDataExist(Menu_ID)) {
                    dbhelper.updateData(Menu_ID, quantity, (Menu_price * quantity));
                } else {
                    dbhelper.addData(Menu_ID, Menu_name, quantity, (Menu_price * quantity));
                }
                checkoutButton.setEnabled(true);
                checkoutButton.setBackgroundColor(R.color.ColorPrimaryDark);
                checkoutButton.setTextColor(Color.WHITE);
            } else {
                dialog.cancel();
                checkoutButton.setEnabled(false);
            }

        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

            // when cancel button clicked close dialog
            dialog.cancel();
        }
    });

    alert.show();
}

现在的问题是

我想在产品列表中显示添加到购物车按钮,我可以直接从产品列表中下订单,而无需打开产品详细信息。

ListActivity就像

public class ActivityMenuList extends AppCompatActivity {

ListView listMenu;
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;

// declare static variable to store tax and currency symbol
public static double Tax;
public static String Currency;

private ActivityMenuDetail details;

// declare adapter object to create custom menu list
AdapterMenuList mla;

// create arraylist variables to store data from server
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
public static ArrayList<Double> Discounted_Price = new ArrayList<Double>();
public static ArrayList<String> Discounted_Value = new ArrayList<String>();
public static ArrayList<Double> Our_Price = new ArrayList<Double>();

String MenuAPI;
String fullAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;

// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
DecimalFormat formatData1 = new DecimalFormat("#.##");
DecimalFormat formatData2 = new DecimalFormat("#.##");
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu_list);

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final android.support.v7.app.ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(R.string.title_menu);
    }

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);

    prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
    listMenu = (ListView) findViewById(R.id.listMenu);
    edtKeyword = (EditText) findViewById(R.id.edtKeyword);
    btnSearch = (ImageButton) findViewById(R.id.btnSearch);
    txtAlert = (TextView) findViewById(R.id.txtAlert);

    // menu API url
    MenuAPI = Config.ADMIN_PANEL_URL+"/api/get-menu-data-by-category-id2.php"+"?accesskey="+Config.AccessKey+"&category_id=";

    // tax and currency API url
    TaxCurrencyAPI = Config.ADMIN_PANEL_URL+"/api/get-tax-and-currency.php"+"?accesskey="+Config.AccessKey;

    // get category id and category name that sent from previous page
    Intent iGet = getIntent();
    Category_ID = iGet.getLongExtra("category_id",0);
    Category_name = iGet.getStringExtra("category_name");
    MenuAPI += Category_ID;

    mla = new AdapterMenuList(ActivityMenuList.this);

    // call asynctask class to request tax and currency data from server
    new getTaxCurrency().execute();

    // event listener to handle search button when clicked
    btnSearch.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            // get keyword and send it to server
            try {
                Keyword = URLEncoder.encode(edtKeyword.getText().toString(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            MenuAPI += "&keyword=" + Keyword;
            IOConnect = 0;
            listMenu.invalidateViews();
            clearData();
            new getDataTask().execute();
        }
    });

    // event listener to handle list when clicked
    listMenu.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            // TODO Auto-generated method stub
            // go to menu detail page
            Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
            iDetail.putExtra("menu_id", Menu_ID.get(position));
            startActivity(iDetail);
        }
    });

    // Using to refresh webpage when user swipes the screen
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(false);
                    IOConnect = 0;
                    listMenu.invalidateViews();
                    clearData();
                    new getDataTask().execute();
                }
            }, 3000);
        }
    });

    listMenu.setOnScrollListener(new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            boolean enable = false;
            if (listMenu != null && listMenu.getChildCount() > 0) {
                boolean firstItemVisible = listMenu.getFirstVisiblePosition() == 0;
                boolean topOfFirstItemVisible = listMenu.getChildAt(0).getTop() == 0;
                enable = firstItemVisible && topOfFirstItemVisible;
            }
            swipeRefreshLayout.setEnabled(enable);
        }
    });

}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_category, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
    case R.id.cart:
        // refresh action
        Intent i = new Intent(ActivityMenuList.this, ActivityCart.class);
        startActivity(i);
        return true;

    case R.id.refresh:
        IOConnect = 0;
        listMenu.invalidateViews();
        clearData();
        new getDataTask().execute();
        return true;            

    case android.R.id.home:
        // app icon in action bar clicked; go home
        this.finish();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

// asynctask class to handle parsing json in background
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{

    // show progressbar first
    getTaxCurrency(){
        if(!prgLoading.isShown()){
            prgLoading.setVisibility(View.VISIBLE);
            txtAlert.setVisibility(View.GONE);
        }
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        // parse json data from server in background
        parseJSONDataTax();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        // when finish parsing, hide progressbar
        prgLoading.setVisibility(View.GONE);
        // if internet connection and data available request menu data from server
        // otherwise, show alert text
        if((Currency != null) && IOConnect == 0){
            new getDataTask().execute();
        }else{
            txtAlert.setVisibility(View.VISIBLE);
        }
    }
}

// method to parse json data from server
public void parseJSONDataTax(){
    try {
        // request data from tax and currency API
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
        HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
        HttpResponse response = client.execute(request);
        InputStream atomInputStream = response.getEntity().getContent();

        BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

        String line;
        String str = "";
        while ((line = in.readLine()) != null){
            str += line;
        }


        // parse json data and store into tax and currency variables
        JSONObject json = new JSONObject(str);
        JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part

        JSONObject object_tax = data.getJSONObject(0); 
        JSONObject tax = object_tax.getJSONObject("tax_n_currency");

        Tax = Double.parseDouble(tax.getString("Value"));

        JSONObject object_currency = data.getJSONObject(1); 
        JSONObject currency = object_currency.getJSONObject("tax_n_currency");

        Currency = currency.getString("Value");


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        IOConnect = 1;
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}

// clear arraylist variables before used
void clearData(){
    Menu_ID.clear();
    Menu_name.clear();
    Menu_price.clear();
    Menu_image.clear();
    Discounted_Value.clear();
    Discounted_Price.clear();
    Our_Price.clear();
}

// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{

    // show progressbar first
    getDataTask(){
        if(!prgLoading.isShown()){
            prgLoading.setVisibility(View.VISIBLE);
            txtAlert.setVisibility(View.GONE);
        }
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        // parse json data from server in background
        parseJSONData();
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        // when finish parsing, hide progressbar
        prgLoading.setVisibility(View.GONE);

        // if data available show data on list
        // otherwise, show alert text
        if(Menu_ID.size() > 0){
            listMenu.setVisibility(View.VISIBLE);
            listMenu.setAdapter(mla);
        }else{
            txtAlert.setVisibility(View.VISIBLE);
        }

    }
}

// method to parse json data from server
public void parseJSONData(){

    clearData();

    try {
        // request data from menu API
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
        HttpUriRequest request = new HttpGet(MenuAPI);
        HttpResponse response = client.execute(request);
        InputStream atomInputStream = response.getEntity().getContent();

        BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

        String line;
        String str = "";
        while ((line = in.readLine()) != null){
            str += line;
        }

        // parse json data and store into arraylist variables
        JSONObject json = new JSONObject(str);
        JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part

        for (int i = 0; i < data.length(); i++) {
            JSONObject object = data.getJSONObject(i); 

            JSONObject menu = object.getJSONObject("Menu");

            Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
            Menu_name.add(menu.getString("Menu_name"));
            Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
            Discounted_Price.add(Double.valueOf(formatData1.format(menu.getDouble("Discounted_Price"))));
            Our_Price.add(Double.valueOf(formatData2.format(menu.getDouble("Our_Price"))));
            Menu_image.add(menu.getString("Menu_image"));
            Discounted_Value.add(menu.getString("Discounted_Value"));

        }


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
}


@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    //mla.imageLoader.clearCache();
    listMenu.setAdapter(null);
    super.onDestroy();
}


@Override
public void onConfigurationChanged(final Configuration newConfig)
{
    // Ignore orientation change to keep activity from restarting
    super.onConfigurationChanged(newConfig);
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    finish();
}

ListAdapter代码

public class AdapterMenuList extends BaseAdapter {

private Activity activity;
    private ActivityMenuDetail details;

public AdapterMenuList(Activity act) {
        this.activity = act;
    }

    public AdapterMenuList(ActivityMenuDetail details) {
        this.details = details;
    }

    public int getCount() {
        return ActivityMenuList.Menu_ID.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

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

        final ViewHolder holder;

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lsv_item_menu_list, null);
            holder = new ViewHolder();

            holder.txtText = (TextView) convertView.findViewById(R.id.txtText);
            holder.txtSubText = (TextView) convertView.findViewById(R.id.txtSubText);
            holder.imgThumb = (ImageView) convertView.findViewById(R.id.ImageCatList);

            holder.discounted_Price = (TextView) convertView.findViewById(R.id.DiscPriceCatList);
            holder.discounted_Value = (TextView) convertView.findViewById(R.id.DiscValueCatList);
            holder.discounted_Price.setTextColor(Color.GRAY);
            holder.discounted_Price.setPaintFlags(holder.discounted_Price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            holder.addtocart = (TextView) convertView.findViewById(R.id.Listaddtocart);
            holder.layout = (LinearLayout) convertView.findViewById(R.id.Listcardview);
            holder.our_Price = (TextView) convertView.findViewById(R.id.Our_Price);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        holder.discounted_Value.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {

                    if(editable.toString().equals("0 % off") | editable.toString().equals("00 % off")){

                        // 1 - You can set empty text
                        holder.discounted_Value.setText("");
                        // 2 - Or you can change the color of the text
                        holder.discounted_Value.setTextColor(Color.TRANSPARENT);
                        // 3 - Or you can change the visibility of the view
                        holder.discounted_Value.setVisibility(View.INVISIBLE);
                        holder.layout.setVisibility(View.GONE);

                    }else{

                        //Here you should undo your code 

                        //1 - if you using method one dose not need to do anything here 
                        // for method 2 
                        holder.discounted_Value.setTextColor(Color.BLACK);
                        // for method 3
                        holder.discounted_Value.setVisibility(View.VISIBLE);
                        holder.layout.setVisibility(View.VISIBLE);

                    }


                }
            });

        holder.txtText.setText(ActivityMenuList.Menu_name.get(position));
        holder.txtSubText.setText("\u20B9" + ActivityMenuList.Menu_price.get(position));
        holder.discounted_Price.setText("\u20B9" + ActivityMenuList.Discounted_Price.get(position));
        holder.discounted_Value.setText(ActivityMenuList.Discounted_Value.get(position)+ " % off");
        holder.our_Price.setText("Our Price" + " " + "\u20B9" + ActivityMenuList.Our_Price.get(position));
        Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityMenuList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);

        return convertView;
    }

    static class ViewHolder {
        TextView txtText, txtSubText, discounted_Price, quantity, discounted_Value, our_Price;
        ImageView imgThumb;
        TextView addtocart;
        LinearLayout layout;
    }

}

任何想法如何在listview项目中添加添加到购物车按钮,我从列表中下订单而不打开新活动。

thankx。

1 个答案:

答案 0 :(得分:0)

是的,这很简单。

只需在每个项目中添加“添加到购物车”选项。

因此,在列表视图中,显示添加到购物车的最右侧,用户可以点击该链接直接添加到购物车。

要获取单击,请在getView()方法的基础适配器中,在该持有者项目上设置单击侦听器(添加到购物车按钮)并在其onClick中执行这些操作。