自定义ListView中的OnClick按钮操作

时间:2016-03-28 11:12:11

标签: android listview

实际上,我试图使用Android Studio实现购物车。主页面中有一个自定义列表视图,其中包含“添加到购物车”按钮。因此,每当我点击按钮时,必须在购物车中添加该项目。但是,我不知道。拜托,伙计们,帮帮我吧。我是新手。

这是产品适配器

mysql> REPLACE INTO table_b SELECT user_id, 
JSON_EXTRACT(body, '$.tel'),
JSON_EXTRACT(body,'$.email'), 
JSON_EXTRACT(body,'$.name') from table_a

以下是主要活动类:

package com.example.raswap.octomatic;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by aurora on 22/03/16.
 */
public class Pro_Adapter extends ArrayAdapter {
    List list = new ArrayList();

    public Pro_Adapter(Context context, int resource) {
        super(context, resource);
    }

    static class DataHandler{
        ImageView img;
        TextView p_name;
        TextView b_name;
        TextView price;
        Button b_atc;
    }

    @Override
    public void add(Object object) {
        list.add(object);
    }

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

    @Override
    public Object getItem(int position) {
        return this.list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row;
        row = convertView;
        DataHandler handler;

        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.e_layout, parent, false);
            handler = new DataHandler();
            handler.img = (ImageView)row.findViewById(R.id.pro_image);
            handler.p_name = (TextView)row.findViewById(R.id.pro_name);
            handler.b_name = (TextView)row.findViewById(R.id.brand);
            handler.price = (TextView)row.findViewById(R.id.pricing);
            handler.b_atc = (Button)row.findViewById(R.id.atc);
            row.setTag(handler);
        }else{
            handler = (DataHandler)row.getTag();
        }

        Product_data_provider dataProvider;
        dataProvider = (Product_data_provider)this.getItem(position);

        handler.img.setImageResource(dataProvider.getPro_img_resource());
        handler.p_name.setText(dataProvider.getPro_name());
        handler.b_name.setText(dataProvider.getBr_name());
        handler.price.setText(dataProvider.getPricing());


        return row;
    }
}

以下是产品数据提供商类:

package com.example.raswap.octomatic;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class E_shop extends Activity {

    ListView listView;
    int[] emage = {R.drawable.gb32, R.drawable.tb1, R.drawable.dvd};
    String[] pro_name;
    String[] br_name;
    String[] price;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_e_shop);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_titlebar);
        View z = findViewById(R.id.oct_logo);
        z.setClickable(true);
        z.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(E_shop.this, MainActivity.class));
            }
        });
        View x = findViewById(R.id.for_user_info);
        x.setClickable(true);
        x.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(E_shop.this, UserInformation.class));
            }
        });
        Pro_Adapter adapter = new Pro_Adapter(getApplicationContext(),R.layout.e_layout);
        ListView listView = (ListView)findViewById(R.id.e_list);
        listView.setAdapter(adapter);
        pro_name = getResources().getStringArray(R.array.nameOfProduct);
        br_name = getResources().getStringArray(R.array.branding);
        price = getResources().getStringArray(R.array.pricing);

        int i = 0;

        for(String pro: pro_name){
            Product_data_provider dataProvider = new Product_data_provider(emage[i],pro, br_name[i], price[i]);
            adapter.add(dataProvider);
            i++;
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch(position){
                    case 0:
                        Intent newActivity = new Intent(E_shop.this, Product_Desc.class);
                        newActivity.putExtra("pro_emage",R.drawable.gb32);
                        newActivity.putExtra("title","Kingston 32Gigs Pen Drive");
                        newActivity.putExtra("desc", "Store a huge collection of data in a generous 32GB space of this Kingston pen drive and carry it along. It has a sleek design with a smooth finish, and a pretty-looking charm bearing the Kingston logo dangles from this pen drive. Featured in a size of 3 x 1.2 x 0.5 cm, this Kingston 32GB pen drive weighs only 5g. You can easily tuck it away in the pocket of your laptop bag, purse or your shirt pocket with its compact and light weight.");
                        startActivity(newActivity);
                        break;
                    case 1:
                        Intent Activity1 = new Intent(E_shop.this, Product_Desc.class);
                        Activity1.putExtra("pro_emage",R.drawable.tb1);
                        Activity1.putExtra("title","Samsung 1TB Portable Hard Disk");
                        Activity1.putExtra("desc", "From college to school students, all deal with transferring files, software and applications from various systems that are large in size. With the advancements in media technology on the rise, we require a large amount of space to store our data. Even most of the growing companies require a secure means of storing data for analyses. All of this embarks on the need for a reliable hard disk. The top quality brand of Samsung brings you this sleek and portable hard drive ideally designed for continuous usage. Now you can store 2TB of diverse data easily. This, sleek hard disk comes with 36 months warranty. The body of this drive has a smart construction. The Samsung external hard disk comes in a sturdy design.");
                        startActivity(Activity1);
                        break;
                    case 2:
                        Intent Activity2 = new Intent(E_shop.this, Product_Desc.class);
                        Activity2.putExtra("pro_emage", R.drawable.dvd);
                        Activity2.putExtra("title", "A pack of 50 DVD's");
                        Activity2.putExtra("desc", "Create and store digital video, audio and multimedia files, Stores up to 4.7GB or more than 2 hours of MPEG2 video, Has 7 times the storage capacity of a CDR, Sony branded 16X DVD-R in a 100 pack Spindle, AccuCORE Technology");
                        startActivity(Activity2);
                        break;
                }
            }
            @SuppressWarnings("unused")
            public void onClick(View v){

            }
        });


    }
}

现在,自定义ListView XML文件:

package com.example.raswap.octomatic;

/**
 * Created by aurora on 22/03/16.
 */
public class Product_data_provider {
    private int pro_img_resource;
    private String pro_name;
    private String  br_name;
    private String pricing;

    public int getPro_img_resource() {
        return pro_img_resource;
    }

    public Product_data_provider(int pro_img_resource, String pro_name, String br_name, String pricing){
        this.setPro_img_resource(pro_img_resource);
        this.setPro_name(pro_name);
        this.setBr_name(br_name);
        this.setPricing(pricing);
    }

    public void setPro_img_resource(int pro_img_resource) {
        this.pro_img_resource = pro_img_resource;
    }

    public String getPro_name() {
        return pro_name;
    }

    public void setPro_name(String pro_name) {
        this.pro_name = pro_name;
    }

    public String getBr_name() {
        return br_name;
    }

    public void setBr_name(String br_name) {
        this.br_name = br_name;
    }

    public String getPricing() {
        return pricing;
    }

    public void setPricing(String pricing) {
        this.pricing = pricing;
    }
}

最后是主要的布局XML文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/oneL"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/pro_image"
                android:src="@drawable/gb32"
                android:layout_width="160dp"
                android:layout_height="match_parent" />
            <LinearLayout
                android:background="#afeeee"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">


                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:text="Product Name"
                    android:id="@+id/pro_name"
                    android:textColor="#000"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Branding"
                    android:id="@+id/brand"
                    android:textColor="#000"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="10dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:text="Price"
                    android:textColor="#000"
                    android:id="@+id/pricing"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp" />

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Add to Cart"
                    android:id="@+id/atc" />
            </LinearLayout>


        </LinearLayout>
        <View
            android:layout_below="@+id/oneL"
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:background="#000"/>
    </RelativeLayout>
</RelativeLayout>

5 个答案:

答案 0 :(得分:2)

在Pro_Adapter的getView()方法中添加按钮的OnClick事件,就像在活动'onCreate()方法中一样。

答案 1 :(得分:0)

在适配器类中实现OnClickListener并首先获取Button,然后在获取事件时执行其他任务。如果您需要回调主活动类,请实现您自己的监听器。关注链接enter link description here

答案 2 :(得分:0)

将onClickListener添加到ListAdapter的getView()中的Button。

答案 3 :(得分:0)

如果你想要处理事件点击按钮,我认为你应该回答set button onclick event for every row of listview

答案 4 :(得分:0)

你可以试试这个。 更改自定义Listview xml文件。

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add to Cart"
    android:onClick="AddCart"
    android:id="@+id/atc" />

在MainActivity中

    public void AddCart(View v) 
    {

        LinearLayout vwParentRow = (LinearLayout)v.getParent();

        TextView child = (TextView)vwParentRow.getChildAt(0);

        child.setText("I've been clicked!");
        vwParentRow.refreshDrawableState();      
    }