当前位置: 首页 > 知识库问答 >
问题:

带有Imageview、TextView的自定义列表视图

汪修诚
2023-03-14

所以我正在创建一个列表视图,其中每一行都有一个Imageview(用于预览图像)、一个textView和一个按钮(用于删除图像)。

问题:

单击该项目的

但有时代码工作正常,有时只是显示错误的项目编号。

更新:

我忘了补充,文本视图中显示的值是:“标志:#”其中#是该项目的当前计数号。我不能理解的总是正确的,但不是我得到的祝酒词: s

背景工作:

页面顶部有一个按钮,用户可以通过该按钮单击照片,当他从摄像头应用程序返回时,列表视图将得到更新

代码:

public class PicMgr extends ListActivity {

    public String storeID;

    public String date;

    TextView picMsg;

    DBAdapter dbEngine = new DBAdapter(this);

    ProgressDialog PDpicTasker;
    private static final String DATASUBDIRECTORY = "pics";
    private static int TAKE_PICTURE = 1;
    public String fIMGname;
    public static String outletpicpathIO;
    private Uri outputFileUri;
    public String fnameIMG;

    public static String[] imgs;
    public static String[] comments;

    private EfficientAdapter adap;

    public static String[] dataLV;

private void TakePhoto() {


        fIMGname = storeID + "_"+ date;

        dbEngine.open();
        //String fIMGname;
                        int countExistingPics = 0;
                        countExistingPics = dbEngine.getExistingPicNos(storeID);
                        countExistingPics = countExistingPics + 1;
                        fIMGname = fIMGname + "_" +countExistingPics;
                        dbEngine.close();

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File dirORIGimg = new File(Environment.getExternalStorageDirectory(),DATASUBDIRECTORY);
        if (!dirORIGimg.exists()) {
            dirORIGimg.mkdirs();
        }

        //newfilename = "newfilename123";
        File file = new File(dirORIGimg, fIMGname + ".jpg");

        //Toast.makeText(getApplicationContext(), "inside TakePhoto(): "+newfilename, Toast.LENGTH_SHORT).show();

        outputFileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(intent, TAKE_PICTURE);

    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    System.out.println("GetPic- onActivityResult - resultCode: "+resultCode);

    if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK) {
        // ShowMessage(outputFileUri.toString());
        //if (data != null) {
            Toast.makeText(getApplicationContext(),outputFileUri.toString(), Toast.LENGTH_SHORT).show();
            System.out.println("outputFileUri.toStr: "+outputFileUri.toString());

            outletpicpathIO = outputFileUri.toString().trim();

            if(!outletpicpathIO.isEmpty()){
                try {
                    new GetCompressedPic().execute().get();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        //}
    }

}

    private class GetPicPath extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("GetPicPathTasker", "Ready to get start -GetCompressedPic-");

        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
            runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            TakePhoto(); // get pic
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });




            } catch (Exception e) {
                Log.i("GetPicPathTasker", "GetCompressedPic Failed!", e);
            }

            finally {

                Log.i("GetPicPathTasker", "GetCompressedPic Completed...");
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            Log.i("GetPicPathTasker", "GetCompressedPic Cancelled");
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Log.i("GetPicPathTasker", "GetCompressedPic cycle completed");

        }
    }

    private class GetCompressedPic extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("PicBGtasker", "Ready to get start -GetCompressedPic-");

            PDpicTasker = ProgressDialog.show(PicMgr.this, null, null);
            //PDpicTasker.setContentView(R.layout.loader);
            PDpicTasker.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Options opts = new BitmapFactory.Options();
                opts.inSampleSize = 2;   // for 1/2 the image to be loaded
                //Bitmap finalBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(outletpicpathIO, opts), 640, 480, false);
                System.out.println("outletpicpathIO: "+outletpicpathIO);

                fnameIMG = new File(outletpicpathIO).getAbsolutePath();
                fnameIMG = fnameIMG.replace("/file:", "");
                fnameIMG = fnameIMG.trim();
                System.out.println("fnameIMG: "+fnameIMG);


                Bitmap finalBitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(fnameIMG), 640, 480, false);
                //Bitmap finalBitmap = BitmapFactory.decodeFile(outletpicpathIO);

                dbEngine.open();

                dbEngine.savePicPath(storeID, fnameIMG);
                dbEngine.close();

                ByteArrayOutputStream streamIMG = new ByteArrayOutputStream();
                File dir = new File(Environment.getExternalStorageDirectory(),DATASUBDIRECTORY);
                if (!dir.exists()) {
                    dir.mkdirs();
                }


                String exportFileName = fIMGname+".jpg"; 
                File fileIMG = new File(dir, exportFileName);
                fileIMG.createNewFile();

                finalBitmap.compress(Bitmap.CompressFormat.JPEG, 50, streamIMG);

                FileOutputStream fo = new FileOutputStream(fileIMG);
                fo.write(streamIMG.toByteArray());
                fo.close();

            } catch (Exception e) {
                Log.i("PicBGtasker", "GetCompressedPic Failed!", e);
            }

            finally {

                Log.i("PicBGtasker", "GetCompressedPic Completed...");
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            Log.i("PicBGtasker", "GetCompressedPic Cancelled");
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Log.i("PicBGtasker", "GetCompressedPic cycle completed");
            PDpicTasker.dismiss();
        }
    }
    // ><

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic_mgr);


        Intent StoreData = getIntent();

        storeID = StoreData.getStringExtra("storeID");

        date = StoreData.getStringExtra("date");

        System.out.println("storeID >> "+storeID);

        picMsg = (TextView)findViewById(R.id.textView1_PicMsg);


        Button outletPic = (Button) findViewById(R.id.Button01_outletpic);
        outletPic.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v2) {

                //TakePhoto(); // get pic

                //async(S)
                try {
                    new GetPicPath().execute().get();
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (ExecutionException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });

        Button saveNcont = (Button) findViewById(R.id.picMgr_saveNcont);
        saveNcont.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v2) {

                /*dbEngine.open();
                dbEngine.savePicPath(storeID, fnameIMG);
                dbEngine.close();*/

                // save comments

            }
        });

         Button backk = (Button) findViewById(R.id.picMgr_back);
         backk.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v2) {

                    finish();

                }
            });


    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        //

        picMsg.setText("Please Click on \"Take Photograph\" button to start taking Pictures");

        dbEngine.open();
        int maxLIMIT = dbEngine.getExistingPicNos(storeID);

        System.out.println("maxLIMIT existing pics count: "+maxLIMIT);

        if(maxLIMIT > 0){

            imgs = dbEngine.getImgsPath(storeID);
            comments = dbEngine.getImgsComment(storeID);


            dataLV=new String[maxLIMIT];
            for(int limitx = 0; limitx < maxLIMIT; limitx++){

                dataLV[limitx]=""+limitx;
            }


            System.out.println("dataLV:"+dataLV.toString());

            picMsg.setText("Please \"Delete\" non-required Photographs shown below \nor Click on \"Take Photograph\" button to start taking more Pictures");


            adap = new EfficientAdapter(this);
            setListAdapter(adap);

        }


        //
        dbEngine.close();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Toast.makeText(this, "Click-" + String.valueOf(position),
                Toast.LENGTH_SHORT).show();
    }

    public static class EfficientAdapter extends BaseAdapter implements
            Filterable {
        private LayoutInflater mInflater;
        private Bitmap mIcon1;
        private Context context;

        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);
            this.context = context;
        }

        /**
         * Make a view to hold each row.
         * 
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid
            // unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;
            // When convertView is not null, we can reuse it directly, there is
            // no need
            // to reinflate it. We only inflate a new View when the convertView
            // supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listview_layout, null);
                // Creates a ViewHolder and store references to the two children
                // views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.textLine = (TextView) convertView
                        .findViewById(R.id.textLine);
                holder.iconLine = (ImageView) convertView
                        .findViewById(R.id.iconLine);

                holder.txt = (EditText) convertView.findViewById(R.id.txt);

                holder.buttonLine = (Button) convertView
                        .findViewById(R.id.buttonLine);

                convertView.setOnClickListener(new OnClickListener() {
                    private int pos = position;

                    @Override
                    public void onClick(View v) {
                        Toast.makeText(context, "Click-" + String.valueOf(pos),
                                Toast.LENGTH_SHORT).show();
                    }
                });
                holder.buttonLine.setOnClickListener(new OnClickListener() {
                    private int pos = position;

                    @Override
                    public void onClick(View v) {
                        Toast.makeText(context,
                                "Delete-" + String.valueOf(pos),
                                Toast.LENGTH_SHORT).show();
                    }
                });

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }
            // Get flag name and id
            String filename = "flag_" + String.valueOf(position);
            /*
             * int id = context.getResources().getIdentifier(filename,
             * "drawable", context.getString(R.string.package_str));
             */

            mIcon1 = BitmapFactory.decodeFile(imgs[position]);

            // Bind the data efficiently with the holder.
            holder.iconLine.setImageBitmap(mIcon1);
            holder.textLine.setText("flag " + String.valueOf(position));

            holder.txt.setText(comments[position]);
            return convertView;
        }

        static class ViewHolder {
            TextView textLine;
            ImageView iconLine;
            EditText txt;
            Button buttonLine;
        }

        @Override
        public Filter getFilter() {
            // TODO Auto-generated method stub
            return null;
        }

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

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return dataLV.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            //String sendBack = PicMgr.dataLV[position];
            return dataLV[position];
        }
    }

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

}

任何意见/建议赞赏...

共有2个答案

朱锐
2023-03-14
holder.buttonLine.setTag(position);
holder.buttonLine.setOnClickListener(new OnClickListener() {
            private int pos = position;

            @Override
            public void onClick(View v) {
                Toast.makeText(context,"Delete-" + String.valueOf(holder.buttonLine.getTag().toString()),
                Toast.LENGTH_SHORT).show();
            }
       });
薄瑞
2023-03-14
  1. ListView有一个方法setOnItemClickListener(),如果你想要一个行的监听器,你不必做转换View.setOnClickListener
  2. 只有当转换视图为空时,才会在该按钮上设置监听器。这意味着当transtView被回收时,您不会更改侦听器(这就是为什么它工作不好)。你应该这样做:

公共视图getView(最终int位置,视图convertView,视图组父对象){ViewHolder holder holder;if(convertView==null){convertView=mInflater.inflate(R.layout.listview_layout,null);holder=new ViewHolder();holder.textLine=(TextView)convertView.findViewById(R.id.textLine);holder.iconLine=(ImageView)convertView.findViewById(R.id.iconLine);

    holder.txt = (EditText) convertView.findViewById(R.id.txt);

    holder.buttonLine = (Button) convertView
            .findViewById(R.id.buttonLine);

    holder.buttonLine.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(context,
                    "Delete-" + v.getTag().toString(),
                    Toast.LENGTH_SHORT).show();
        }
    });

    convertView.setTag(holder);
} else {
    // Get the ViewHolder back to get fast access to the TextView
    // and the ImageView.
    holder = (ViewHolder) convertView.getTag();
}
holder.buttonLine.setTag(position);
//rest of the method
return convertView;

}

 类似资料:
  • 我想创建一个从ArrayList中获取数据的listview。这是单行的一个示例 默认情况下,该复选框是禁用的,它只在一个SeloncemClickListener中激活(用于多次删除)。 最后一个图像是一个菜单按钮,它打开菜单列表以进行删除、共享等操作。 我不知道如何制作我的定制适配器。使用simplearrayadapter很简单,但我不能使用自定义行。有人帮忙吗?吻,塔季扬娜。对不起我的英语

  • 我有一个自定义列表视图,其中有一个文本视图和三个图像视图。单击图像视图,我想开始一个新的活动,并将特定位置的数据传递给下一个活动。但我得到了空指针异常。 我用这个做参考http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html 这是我的密码。这是主要活动 我在这一行遇到了例外 我该怎么做?请帮帮我。 这是我的

  • 本文向大家介绍Android自定义带拼音音调Textview,包括了Android自定义带拼音音调Textview的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了Android自定义带拼音音调Textview的具体代码,供大家参考,具体内容如下 1.拼音textview,简单的为把拼音数组和汉字数组结合在一起多行显示 2.汉字转拼音使用 implementation ‘com.bel

  • 我试着在谷歌和专门的论坛上搜索这个问题,但什么也没找到。 我的问题是:我有一个带代表的列表视图,根据Qt指南从C模型中读取数据。 当项目超出可见区域时,我不能使用滚动条,但我会得到如下结果: 其中3点将被启用/禁用,以告诉列表可以根据视图中的项目数量向上或向下滚动。 总之,它就像一个定制的滚动条。 你对实现这种行为有什么建议吗?或者我可以看看哪里?谢谢你。克里斯蒂亚诺

  • 我正在对JSONArray进行排序,并在自定义列表视图中显示它们,但排序后数据在自定义列表视图中没有改变。 下面是fab按钮选择要执行的排序的代码: 在fab按钮中进行选择后,单击i sort json Array。下面是解析json数组的代码: 我使用`Adapter.NotifyDataSetChanged();但我的自定义列表不会影响排序。请建议我怎么做。

  • 我使用这段代码来最大化和恢复我的自定义表单。但是当窗体最大化时,它仍然可以拖动,我使用计时器来拖动窗体。