android - 自定义 ListView 中的 OnClick 按钮操作

标签 android listview

实际上,我正在尝试使用 Android Studio 实现购物车。主页中有一个自定义 ListView ,包括一个“添加到购物车”按钮。因此,每当我单击按钮时,都必须将商品添加到购物车中。但是,我不知道。请大家帮帮我。我是新手。

这是产品适配器

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;
    }
}

这是主 Activity 类:

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){

            }
        });


    }
}

这是产品数据提供者类:

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;
    }
}

现在,自定义 ListView 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>

最后是主布局 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.raswap.octomatic.E_shop">

    <ListView
        android:id="@+id/e_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>

最佳答案

在 Pro_Adapter 的 getView() 方法中添加按钮的 OnClick 事件,就像您通常在 Activity 的 onCreate() 方法中所做的那样。

关于android - 自定义 ListView 中的 OnClick 按钮操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36261152/

相关文章:

android - 如何获得每个进程和进程空闲 CPU 时间的准确 CPU 使用率

android - 在 ActionBar 中设置 Item 位置

android - 自定义 ListView 适配器 [Android]

java - Android,如何将ListView适配器的位置减1

C++ 平铺 View 中的 Virtual ListView,无法显示子项

android - 移动应用程序的自签名 SSL 与 Diffie-Hellman 交换?

android - 强制主题为@android :drawables supporting low level APIs

android - 为什么我不能在 Android 应用程序中使用 PayPal Rest API?

android - 将一个从适配器类动态变化的整数变量传递给 Activity

c# - 更新绑定(bind) Observable 集合的一个元素