为listview的每一行设置按钮onclick事件

2024-01-02

我使用 AsyncTask 通过 json 解析填充 listview。在列表视图的每一行中我都有一个按钮。我想为他们编写 onclickLister 。

我希望,当我单击“添加到购物车”时,将名称、价格和数量的数据保存到 sqlite。

public void addtocart(){
        Button btnaddtocart=(Button)findViewById(R.id.btnInsertToCart);
        final TextView tname=(TextView)findViewById(R.id.nameNewItem);
        final EditText eqty=(EditText)findViewById(R.id.updateQty);
        final TextView tprice=(TextView)findViewById(R.id.priceNewItem);

        btnaddtocart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if(eqty.getText().toString().equalsIgnoreCase("")){
                        Toast.makeText(getApplicationContext(),"Please enter the Quantity.",Toast.LENGTH_LONG).show();
                    }
                    else { SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
                        database.execSQL("CREATE TABLE IF NOT EXISTS CART(id integer primary key autoincrement,title VARCHAR(150),qty INT(10),price INT(10));");
                        database.execSQL("INSERT INTO CART(title,qty,price) VALUES('" + tname.getText().toString() + "'," + Integer.parseInt(eqty.getText().toString())+","
                                + Integer.parseInt(tprice.getText().toString())+");");

                        database.close();
                        eqty.setText(null);

                        //hide keyboard
                        InputMethodManager imm = (InputMethodManager)getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(eqty.getWindowToken(), 0);

                        Toast.makeText(getApplicationContext(),"Add to Cart",Toast.LENGTH_LONG).show();}

                }
                catch (Exception ex){
                    Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_LONG).show();
                }
            }
        });

但我的问题是我应该编写以下代码的哪一部分:

public class Update extends Activity {
    ListView list;
    Button Btngetdata;
    ProgressDialog pDialog;
    ArrayList<HashMap<String, String>> newItemlist = new ArrayList<HashMap<String, String>>();
    private static final String TAG_ITEM = "NewItem";
    private static final String TAG_NAME = "name";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_PRICE = "price";
    ConnectionDetector cd;
    Boolean isInternetPresent = false;
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.updateapp);
        pDialog = new ProgressDialog(Update.this);
        pDialog.setMessage("Getting Data ...");

        newItemlist = new ArrayList<HashMap<String, String>>();
        Btngetdata = (Button)findViewById(R.id.getdata);
        cd = new ConnectionDetector(getApplicationContext());
        Btngetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isInternetPresent = cd.isConnectingToInternet();
                if (isInternetPresent) {
                new JSONParse().execute();   }
                else {
                    Toast.makeText(getApplicationContext(),"You don't have internet connection.",Toast.LENGTH_LONG).show();
                }

            }
        });


    }
    private class JSONParse extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }
        @Override
        protected Void doInBackground(String... args) {
            try {
                Log.i("...............", "Hello..............");
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpPost = new HttpGet("http://www.karocellen.com/newItem.json");
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                String jsonstring = EntityUtils.toString(httpEntity);
                Log.i("...............",jsonstring);
                JSONObject json = new JSONObject(jsonstring);
                JSONArray newitem = json.getJSONArray(TAG_ITEM);
                for(int i = 0; i < newitem.length(); i++){
                    JSONObject c = newitem.getJSONObject(i);
                    String name = c.getString(TAG_NAME);
                    String description = c.getString(TAG_DESCRIPTION);
                    String  price = c.getString(TAG_PRICE);
                    Log.i("...............",name);
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_NAME, name);
                    map.put(TAG_DESCRIPTION, description);
                    map.put(TAG_PRICE, price);
                    newItemlist.add(map);
                }

            }   catch (Exception ex){


            }
            return null;

        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            list=(ListView)findViewById(R.id.listupdate);
            ListAdapter adapter = new SimpleAdapter(Update.this, newItemlist,
                    R.layout.updateapprow,
                    new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] {
                    R.id.nameNewItem,R.id.descriptionNewItem, R.id.priceNewItem});
            list.setAdapter(adapter);              

    }
    }

使用自定义适配器。

您需要了解列表视图的工作原理

ListView的回收机制是如何工作的 https://stackoverflow.com/questions/11945563/how-listviews-recycling-mechanism-works

将活动上下文和 NewItems 列表传递给自定义适配器的构造函数。

   @Override
   protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            list=(ListView)findViewById(R.id.listupdate);
            CustomAdapter cus = new CustomAdapter(MainActivtiy.this,newItemlist); 
            list.setAdapter(cus);              

    }

使用带有文本视图和按钮的自定义布局。命名它list_item.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="33dp"
        android:layout_marginTop="40dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView2"
        android:layout_marginLeft="34dp"
        android:layout_toRightOf="@+id/textView2"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="20dp"
        android:text="Button" />

</RelativeLayout>

膨胀布局、初始化和更新视图。在按钮上设置侦听器执行所需操作。

  public class CustomAdapter extends BaseAdapter
    {
        LayoutInflater mInlfater;
        ArrayList<HashMap<String,String>> list;
        public CustomAdapter(Context context,ArrayList<HashMap<String,String>> list) 
        {
             mInlfater = LayoutInflater.from(context);
             this.list =list;
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder holder;
            if(convertView ==null)
            {
                convertView = mInlfater.inflate(R.layout.list_item,false);
                holder = new ViewHolder();
                holder.b1 = (Button)convertView.findViewById(R.id.button1);
                holder.tv1 = (TextView)convertView.findViewById(R.id.textView1);
                holder.tv2 = (TextView)convertView.findViewById(R.id.textView2);
                holder.tv3 = (TextView)convertView.findViewById(R.id.textView3);
                convertView.setTag(holder);

            }
            else
            {
                holder =(ViewHolder) convertView.getTag();
            }
            HashMap<String,String> map = list.get(position);
            holder.tv1.setText(map.get("name"));
                holder.tv2.setText(map.get("description"));
                holder.tv3.setText(map.get("price"));
                holder.b1.setOnClickListener(new OnClickListener()
                {

                @Override
                public void onClick(View v) {
                // TODO Auto-generated method stub

                }


               });
            return convertView;
        }
        static class ViewHolder
        {
            Button b1;
            TextView tv1,tv2,tv3;
        }
    } 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为listview的每一行设置按钮onclick事件 的相关文章

  • 如何重试已消耗的 Observable?

    我正在尝试重新执行失败的已定义可观察对象 一起使用 Retrofit2 和 RxJava2 我想在单击按钮时重试特定请求及其订阅和行为 那可能吗 service excecuteLoginService url tokenModel Ret
  • android中向sqlite中插入大量数据

    目前 我必须一次向我的 Android 中插入超过 100 亿条数据 然而 内存不足的问题会使程序崩溃 sqlite 插入测试非常简单 只需使用 for 循环生成 sql 插入命令并通过 开始 和 提交 进行包装 private Array
  • 无法获取log.d或输出Robolectrict + gradle

    有没有人能够将 System out 或 Log d 跟踪从 robolectric 测试输出到 gradle 控制台 我在用Robolectric Gradle 测试插件 https github com robolectric robo
  • 谷歌坐标认证

    当我尝试连接到 Google 坐标时 总是出现异常GoogleAuthException 我拥有 Google 地图协调中心许可证 我确实使用我的包应用程序名称和 SHA1 在 google 控制台中创建了我的客户端 ID 我将权限添加到清
  • 如何以编程方式检查 AndroidManifest.xml 中是否声明了服务?

    我正在编写一个库 该库提供了一项服务 其他开发人员可以通过将其包含在他们的项目中来使用该服务 因此 我无法控制 AndroidManifest xml 我在文档中解释了要做什么 但一个常见的问题是人们忽略了将适当的 标记添加到其清单中 或者
  • Android Activity 生命周期函数基础知识

    我正在测试这段代码 它显示活动所处的状态 public class Activity101Activity extends Activity String tag Lifecycle Called when the activity is
  • 在画布上绘图

    我正在编写一个 Android 应用程序 它可以在视图的 onDraw 事件上直接绘制到画布上 我正在绘制一些涉及单独绘制每个像素的东西 为此我使用类似的东西 for int x 0 x lt xMax x for int y 0 y lt
  • Android 模拟器插件无法初始化后端 EGL 显示

    我在 Cloudbees 上设置了 Jenkins 作业 并且可以在那里成功签出并编译我的 Android 项目 现在我想在 android 模拟器中运行一些 JUnit 测试并添加 Android 模拟器插件 我将 显示模拟器窗口 选项设
  • 是否有 ADB 命令来检查媒体是否正在播放

    我想使用 ADB 命令检查根植于终端的外部设备中是否正在播放音频 视频 我无法找到任何 ADB 命令 如果有 我尝试过 adb shell dumpsys media player 我想要一个命令来指定视频是否正在运行 您可以使用以下命令查
  • 在gradle插件中获取应用程序变体的包名称

    我正在构建一个 gradle 插件 为每个应用程序变体添加一个新任务 此新任务需要应用程序变体的包名称 这是我当前的代码 它停止使用最新版本的 android gradle 插件 private String getPackageName
  • 如何使用 IF 检查 TextView 可见性

    我有一个 onCheckedChangeListener 来根据选择的单选按钮显示文本视图 我有 1 个疑问和 1 个难题 想知道是否有人可以帮助我 问题 您能否将单选组默认检查值设置为 否 单选按钮 以便一开始就不会检查任何内容 问题 如
  • Ubuntu 16.04 - Genymotion:找不到 /dev/hw_random

    I install Genymotion on the Ubuntu 16 04 64Bit I created a virtual emulator for Android 6 0 then I run this emulator but
  • 在 SQLite 中搜索时排除 HTML 标签和一些 UNICODE 字符

    更新 4 我已经成功运行了firstchar例如 但现在的问题是使用regex 即使包含头文件 它也无法识别regex操作员 有什么线索可以解决这个问题吗 更新 2 我已经编译了sqlite3我的项目中的库 我现在正在寻找任何人帮助我为我的
  • 我想实现下面的布局,按钮应该在屏幕底部,当惰性列被填充时,按钮不应该出去

    顶部有惰性列 惰性列下方有输入电话号码布局并从电话簿布局添加联系人 我希望当未添加联系人时此布局位于顶部 当我添加大量联系人时输入电话号码并添加电话簿布局中的联系人会随着惰性列滚动并移出屏幕 我不让他们走出屏幕 当接触较多时 它们必须粘在底
  • 我的设备突然没有显示在“Android 设备选择器”中

    我正在使用我的三星 Galaxy3 设备来测试过去两个月的应用程序 它运行良好 但从今天早上开始 当我将设备连接到系统时 它突然没有显示在 Android 设备选择器 窗口中 我检查过 USB 调试模式仅在我的设备中处于选中状态 谁能猜出问
  • Android向menuItem添加子菜单,addSubMenu()在哪里?

    我想根据我的参数以编程方式将 OptionsMenu 内的子菜单添加到 menuItem 中 我检查了android sdk中的 MenuItem 没有addSubMenu 方法 尽管你可以找到 hasSubMenu 和 getSubMen
  • .isProviderEnabled(LocationManager.NETWORK_PROVIDER) 在 Android 中始终为 true

    我不知道为什么 但我的变量isNetowrkEnabled总是返回 true 我的设备上是否启用互联网并不重要 这是我的GPSTracker class public class GPSTracker extends Service imp
  • Android 套接字和 asynctask

    我即将开始制作一个应该充当 tcp 聊天客户端的应用程序 我一直在阅读和阅读 我得出的结论是最好 如果不需要 将我的套接字和异步任务中的阅读器 问题是我不确定从哪里开始 因为我是 Android 新手 这至少对我来说是一项艰巨的任务 但据我
  • Firebase 添加新节点

    如何将这些节点放入用户节点中 并创建另一个节点来存储帖子 我的数据库参考 databaseReference child user getUid setValue userInformations 您需要使用以下代码 databaseRef
  • 如何将 google+ 登录集成到我的 Android 应用程序中?

    大家好 实际上我需要通过我的应用程序从 google 登录人们 现在我阅读了 google 上的文档 其中指出 要允许用户登录 请将 Google Sign In 集成到您的应用中 初始化 GoogleApiClient 对象时 请求 PL

随机推荐

  • python:如何根据 1 个列表中的内容从 2 个列表中删除值

    我有 2 个号码列表 其中一个名为xVar另一个叫yVar 我将使用这两个元素在图表上绘制 X 和 Y 值 它们都具有相同数量的元素 通常情况下 我只会绘制 ax scatter xVar yVar s 2 color tomato 我想从
  • 访问 symfony 2 中的 AppKernel 环境变量

    我正在使用 symfony 2 我们有 2 个配置 开发版和生产版 我需要知道是否可以找出我在实体或模型中使用的是哪一个 我正在寻找与 AppKernel php 中找到的代码类似的内容 this gt getEnvironment 如果我
  • 使用 Next.js 检索服务器端数据并保存在上下文中

    我希望能够从服务器端 API 检索数据 并将其加载到 React 上下文中 以便使其可供我的应用程序中的任何组件使用 我尝试过各种事情 但似乎没有什么能让我完全做我想做的事 我尝试过的一些事情包括 getServerSideProps 这允
  • Codeigniter 删除所有 html 标签

    你如何删除ALL带 codeigniter 的 HTML 标签 我猜你必须使用 PHP 函数strip tags 但我想要类似 XSS 过滤的全局设置 Thanks 如果您指的是使用input方法 是的 你可以从技术上开放system li
  • Angular2 反应式表单 - 使用下拉菜单设置表单字段的默认值

    如何设置 Angular 2 反应表单中所有表单字段的默认值 这里是plnkr https plnkr co edit GKguMzZbr0kzrraPP73f p preview重现问题 下面的代码不会更新下拉值 因为它有一个与之关联的对
  • 使用 R 检索期刊论文的引文

    使用 R 我想获取引用科学期刊论文的文章列表 我所拥有的唯一信息是文章的标题 例如 用福林苯酚试剂测量蛋白质 有人能够通过制作一个我可以使用的可复制示例来帮助我吗 这是我到目前为止所尝试的 R 包fulltext似乎很有用 因为它允许检索链
  • 概览显示重复的 EF 查询

    我的 MVC 4 应用程序运行速度太慢 出现问题 我安装了 Glimpse 来分析该应用程序 我想我已经找到了部分问题 我的许多 EF 查询似乎运行了两次 这是我的 HomeController 它正在发出一些警报 HttpGet publ
  • 将 URL 参数传递给redirect_to :root

    这可能是一个非常愚蠢的问题 但几乎不可能通过谷歌搜索答案 是否有可能 如果可以的话如何 做类似的事情 redirect to root registered gt true 然后将链接到http myurl com registered t
  • 如何告诉 scons 使用 C++11 标准

    我无法找到如何告诉 scons 接受 c 11 标准 SConstruct 文件 env Environment CPPPATH usr include boost CPPDEFINES LIBS SCONS CXX STANDARD c
  • 我如何在 FMX 中使用 showmodal?

    我正在尝试为我的主 Android 表单创建一个登录表单 所以我做了这样的事情 var CanGo Boolean begin Application Initialize Application CreateForm TForm1 For
  • OpenCV 将一种颜色转换为另一种颜色

    我有一张灰度图像 我想将所有白色像素 纯白色 255 转换为黑色 0 仅那些颜色 而不是所有灰度 我怎样才能做到这一点 谢谢你 罗恩 您可以执行以下操作 使用阈值设置图像inRange http docs opencv org module
  • Rxjava tolist() 未完成

    我的 RxJava 调用链有问题 toList 无法正常工作 我猜想 toList 需要一些东西来完成 这就是它被卡住的原因 但我不知道如何解决这个问题 The code mModel getLocations flatMapIterabl
  • “ApacheCordovaToolsPackage”包未正确加载

    我刚刚安装了 VS 2015 Professional 并尝试安装 Visual Studio Tools for Apache Cordova 它成功完成 然而 当我尝试为此创建一个新项目时 它就卡在那里了 然后 如果我打开 VS 201
  • Ant 和可用任务 - 如果某些任务不可用怎么办?

    当我使用该任务时 仅当资源 例如文件 可用时 该属性才会设置为 TRUE 如果不是 则该属性未定义 当我打印属性的值时 如果资源可用 则返回 true 否则仅打印属性名称 如果资源是 有没有办法将属性设置为某个值not可用的 我尝试在可用检
  • 请解释一下这个高阶函数的javascript代码

    我正在按照 Eloquent JavaScript 书学习高阶函数 我无法理解这段代码 为什么 布尔值 作为嘈杂的第一个参数传递 这应该是改变其他功能的功能 我只是不明白它是如何工作的 function noisy f return fun
  • 使用可变属性名称反序列化 JSON

    我想反序列化 jsonhere http feiertage jarmedia de api jahr 7Byear 7D 与此类似 BW Neujahrstag datum 2017 01 01 hinweis Heilige Drei
  • Admin 中 Django 的外键参考

    我一直在尝试在 Django admin 中解决这个问题 但仍然找不到文档 In my 模型 py 我有以下代码 from django db import models class Post models Model title mode
  • 将 Mma 7 中的 Caps lock 键重新映射为 Esc

    TLDR 如何在 Mma 7 中将 CapsLock 转换为 ShortNameDelimiter I like pretty text in my mma notebooks and often define functions as f
  • getInstance() 是如何工作的?

    最近我阅读了一些广泛使用以下 getInstance 方法的 C 代码 class S private int some int 0 public static S getInstance static S instance return
  • 为listview的每一行设置按钮onclick事件

    我使用 AsyncTask 通过 json 解析填充 listview 在列表视图的每一行中我都有一个按钮 我想为他们编写 onclickLister 我希望 当我单击 添加到购物车 时 将名称 价格和数量的数据保存到 sqlite pub