在列表视图按钮事件视图、按钮、事件、列表

2023-09-06 14:07:46 作者:不是奇葩难闯天下

我的ListView中,我吹一排包含TextView的和按钮,现在我要处理的点击按钮的事件,美元的适配器C $ CD,我能得到按钮的位置了。但在这里,当我点击按钮,我改变按钮的图像及其工作正常的问题是,当我滚动视图再次更改按钮图像,因为它是因为getview前()方法的再循环查看每一次。

I have listView in which I inflate a row contain textview and button now I want to handle click event of button which coded in adapter and I am able to get the position of button too. But here when I click on button I am changing a image of button its works fine problem is when I scroll the view it again change the image of button as it was before because of getview() Method its recycle view every time.

如何处理上述功能适配器?

How to handle above functionality in adapter?

下面是按钮事件code这是$ C $光盘adpater。

Below is the button event code which is coded in adpater.

holder.download.setTag(position) ;

        holder.download.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                pos =(Integer) v.getTag() ; 
                Log.d("*******************************", ""+pos);
                Constant.buttonStates[pos]=1;   
        pref = activity.getSharedPreferences("status", MODE_PRIVATE);
                SharedPreferences.Editor edit=pref.edit();
                edit.putInt("s",Constant.buttonStates[pos]);
                //edit.putString("s",  Constant.buttonStates.toString());
                edit.commit();

                check[pos]=pref.getInt("s", 1);

                v.setBackgroundResource(R.drawable.right);
                try {
                    new PubDetailsTask().execute("");
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        });

下面是适配器中,我处理一个按钮的事件。

Below is the adapter in which I am handling a button events.

public class PublicationAdapter extends BaseAdapter implements
    DownloadThreadListener {

    private LayoutInflater mInflater;
    private SQLiteDBAssistant sqlliteCity;
    private DownloadThread downloadThread;
    private Handler handler;
    public ImageLoader imageLoader;
    static String videoUrl, downloadImage, downloadVideo, name, url,
        output = "", selId = "";
    int pos, btnpos, tempos;
    JSONArray globalData, arrListFinal;
    Activity activity;
    Bitmap bbicon;
    ArrayList<String> imageUrl = new ArrayList<String>();
    AlertDialog.Builder downloadDialog;
    AlertDialog downloadMsg;
    ViewHolder holder;
    String author[];
    HttpManager httpObject;
        String pub_id = "", title = "", avgrat = "", content = "", authorname = "",
        mediafile = "", docurl = "", thumburl = "", peerrat = "",
        profrat = "", comrat = "", peerrank = "", profrank = "",
        comrank = "", urid = "", uravgrat = "", urrole = "",
        imagePath = "";
    String video_SDpath = "";
    int[] buttonStates;

    public PublicationAdapter(Activity a, JSONArray arrList) {

               httpObject = new HttpManager();
       globalData = arrList;
       activity = a;

       mInflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       imageLoader = new ImageLoader(activity.getApplicationContext());
       Constant.publicationIdArraylist = new ArrayList<String>();
       downloadThread = new DownloadThread(PublicationAdapter.this, activity);
       downloadThread.start();
       handler = new Handler();

       buttonStates = new int[globalData.length()];
       for (int i = 0; i < globalData.length(); i++) {
            buttonStates[i] = 0;
       }

       downloadDialog = new AlertDialog.Builder(a);
       downloadDialog.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    downloadMsg.dismiss();
                }
       });
       downloadMsg = downloadDialog.create();

   }
   public int getCount() {
    return globalData.length();
   }
   public Object getItem(int postionitem) {
    return postionitem;
   }
   public long getItemId(int positionitemId) {
    return positionitemId;
   }
   public void setSelectedPosition(int pos) {
    tempos = pos;
    // inform the view of this change
    notifyDataSetChanged();
       }
   public int getSelectedPosition() {
    return tempos;
   }
   public class ViewHolder {
    TextView twtdata;
    ImageView twtimg;
    TextView twtnm;
    Bitmap image;
    Button download;
   }

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

          View vi = convertView;
          if (convertView == null) {

               vi = mInflater.inflate(R.layout.listrowplaylists, null);

               holder = new ViewHolder();
               holder.twtdata = (TextView) vi.findViewById(R.id.txtauthor);
               holder.twtnm = (TextView) vi.findViewById(R.id.txtlisttitle);
               holder.twtimg = (ImageView) vi.findViewById(R.id.avatar);
               holder.download = (Button) vi.findViewById(R.id.btn_download);

               if (buttonStates[position] == 0)
                 holder.download.setBackgroundResource(R.drawable.downloadicon); //button not clicked   
                           else 
                holder.download.setBackgroundResource(R.drawable.right); // button clicked
               vi.setTag(holder);
        }
        else 
        {
              holder = (ViewHolder) vi.getTag();
        }

        try {

              JSONObject firstObject = globalData.optJSONObject(position);
              Log.i("Publication", firstObject.toString());

              holder.twtnm.setText(firstObject.getString("Title"));
              imageUrl.add(firstObject.optString("ThumbnailUrl"));
              holder.twtimg.setTag(imageUrl.get(position));
              imageLoader.DisplayImage(imageUrl.get(position), activity,
                holder.twtimg);

              Constant.publicationIdArraylist.add(firstObject.getString("Id"));
              Log.i("ID IN LIST", "=================="
                + Constant.publicationIdArraylist.get(position));

             JSONArray firstarray = firstObject.getJSONArray("Authors");
             int len = firstarray.length();
             author = new String[len];

             for (int j = 0; j < firstarray.length(); j++) {
                JSONObject third = firstarray.getJSONObject(j);
                author[j] = authorname = third.getString("AuthorName");
             }
             try {
                holder.twtdata.setText(author[0] + ", " + author[1]);
             } 
             catch (Exception e) {              
             }
       } 
       catch (Exception e) {
               e.printStackTrace();
       }
       holder.download.setTag(position);

       holder.download.setOnClickListener(new OnClickListener() {

              public void onClick(View v) {

                 pos = (Integer) v.getTag();
                 Log.d("*******************************", "" + pos);
                 buttonStates[pos] = 1;
                 v.setBackgroundResource(R.drawable.right);
                 selId = Constant.publicationIdArraylist.get(position);
                 System.out.println("buton clicked id  " + selId);
                 try {
                     new PubDetailsTask().execute("");
                 }
                                 catch (Exception e) {
                 }
             }
       });
       return vi;
}

感谢。

推荐答案

假设你有CustomAdapter.class来填充你的ListView,则:

Lets say you have CustomAdapter.class to populate your listview,then:

public class CustomAdapter extends ArrayAdapter<String> {

        String[] array;
    Context mContext;
    LayoutInflater mInflater;
    int[] buttonStates;

    public CustomAdapter(Context context, int textViewResourceId,
            String[] objects)
    {
        super(context, textViewResourceId, objects);
        array=objects;
        mContext=context;
        mInflater = LayoutInflater.from(context);
        //save all buttons state as 0(not clicked) initially
        buttonStates=new int[objects.length];
            for(int i=0;i<objects.length;i++)
            { 
                   buttonStates[i]=0;
            }  
    }  
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ...
         if(buttonStates[position]==0)
         {
             holder.button.setBackgroundResource(R.drawable.bg_normal);  //set background for button "not clicked"          
         }
         else
         {
             holder.button.setBackgroundResource(R.drawable.bg_pressed);  //set background for button "clicked"                 
         }

         final int pos=position;
         holder.download.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                buttonStates[pos]=1;                
                holder.button.setBackgroundResource(R.drawable.bg_clicked);                
            }
        });         
    }  
}

我已经测试了这个和它的作品对我很好!

I have tested this one and it works fine for me!

编辑:

您需要添加code这几行:

You need to add these lines of code:

if (buttonStates[position] == 0)
         holder.download.setBackgroundResource(R.drawable.downloadicon); // set background for button "not clicked"             
else
         holder.download.setBackgroundResource(R.drawable.right); // set background for button "clicked"

出方如果(convertView == NULL)......否则...... 。所以把那个code你写之前:

out side if(convertView == null)...else.... So put that code just before you write:

holder.download.setOnClickListener(new OnClickListener() {
...}

这将解决您的问题。

当你把它放进如果(convertView == NULL),它将只调用once.so您得到您在您的评论描述我的问题!

When you put it into if(convertView==null),it will called only once.so you are getting the problem you described to me in your comment!