81

我想为onClick项目中使用的按钮添加事件Listview。如何onClick为列表项中的按钮提供事件。

4

10 回答 10

98

在适配器类中

public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = getLayoutInflater();
    View row = inflater.inflate(R.layout.vehicals_details_row, parent, false);
    Button deleteImageView = (Button) row.findViewById(R.id.DeleteImageView);
    deleteImageView.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //...
        }
    });
}

但是您可能会遇到问题 - listView 行不可点击。解决方案:

  • 使 ListView 可聚焦android:focusable="true"
  • 按钮无法聚焦 android:focusable="false"
于 2012-09-26T07:10:59.420 回答
67

您可以onClick在自定义适配器的getView方法中设置事件..
检查链接http://androidforbeginners.blogspot.it/2010/03/clicking-buttons-in-listview-row.html

于 2012-09-26T07:00:15.160 回答
13

试试这个,

public View getView(final int position, View convertView,ViewGroup parent) 
{
   if(convertView == null)
   {
        LayoutInflater inflater = getLayoutInflater();
        convertView  = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
   }

   Button Button1= (Button)  convertView  .findViewById(R.id.BUTTON1_ID);

   Button1.setOnClickListener(new OnClickListener() 
   { 
       @Override
       public void onClick(View v) 
       {
           // Your code that you want to execute on this button click
       }

   });


   return convertView ;
}

它可能会帮助你......

于 2012-09-26T07:51:04.647 回答
4

在 getView 方法内的自定义适配器中:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do things Here 
    }
});
于 2012-09-26T07:04:26.973 回答
2

这已在许多帖子中讨论过,但我仍然无法找到解决方案:

android:focusable="false"
android:focusableInTouchMode="false"
android:focusableInTouchMode="false"

以下解决方案适用于任何 ui 组件:Button、ImageButtons、ImageView、Textview。LinearLayout、RelativeLayout 在 listview 单元格内点击,也会响应 onItemClick:

适配器类 - getview():

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = lInflater.inflate(R.layout.my_ref_row, parent, false);
            }
            final Organization currentOrg = organizationlist.get(position).getOrganization();

            TextView name = (TextView) view.findViewById(R.id.name);
            Button btn = (Button) view.findViewById(R.id.btn_check);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    context.doSelection(currentOrg);

                }
            });

       if(currentOrg.isSelected()){
            btn.setBackgroundResource(R.drawable.sub_search_tick);
        }else{
            btn.setBackgroundResource(R.drawable.sub_search_tick_box);
        }

    }

在这种情况下,您可以将按钮单击的对象传递给活动。(特别是当您希望按钮充当具有选中和未选中状态的复选框时):

    public void doSelection(Organization currentOrg) {
        Log.e("Btn clicked ", currentOrg.getOrgName());
        if (currentOrg.isSelected() == false) {
            currentOrg.setSelected(true);
        } else {
            currentOrg.setSelected(false);
        }
        adapter.notifyDataSetChanged();

    }
于 2015-07-22T06:46:06.773 回答
1

我假设您已经为您的 ListView 定义了自定义适配器。

如果是这种情况,那么您可以onClickListener在自定义适配器的getView()方法中为您的按钮分配。

于 2012-09-26T07:01:31.387 回答
1

ArrayList 和 ArrayAdapter 的类

class RequestClass {
    private String Id;
    private String BookingTime;
    private String UserName;
    private String Rating;

    public RequestClass(String Id,String bookingTime,String userName,String rating){
        this.Id=Id;
        this.BookingTime=bookingTime;
        this.UserName=userName;
        this.Rating=rating;
    }

    public String getId(){return Id; }
    public String getBookingTime(){return BookingTime; }
    public String getUserName(){return UserName; }
    public String getRating(){return Rating; }


}

主要活动:

 ArrayList<RequestClass> _requestList;
    _requestList=new ArrayList<>();
                    try {
                        JSONObject jsonobject = new JSONObject(result);
                        JSONArray JO = jsonobject.getJSONArray("Record");
                        JSONObject object;
                        for (int i = 0; i < JO.length(); i++) {
                            object = (JSONObject) JO.get(i);

                            _requestList.add(new RequestClass( object.optString("playerID"),object.optString("booking_time"),
                                    object.optString("username"),object.optString("rate") ));
                        }//end of for loop

                        RequestCustomAdapter adapter = new RequestCustomAdapter(context, R.layout.requestlayout, _requestList);
                        listView.setAdapter(adapter);

自定义适配器类

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by wajid on 1/12/2018.
 */

class RequestCustomAdapter extends ArrayAdapter<RequestClass> {
    Context mContext;
    int mResource;
    public RequestCustomAdapter(Context context, int resource,ArrayList<RequestClass> objects) {
        super(context, resource, objects);
        mContext=context;
        mResource=resource;
    }
    public static class ViewHolder{
        RelativeLayout _layout;
        TextView _bookingTime;
        TextView _ratingTextView;
        TextView _userNameTextView;
        Button acceptButton;
        Button _rejectButton;
    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup parent){
       final ViewHolder holder;
        if(convertView == null) {
            LayoutInflater inflater=LayoutInflater.from(mContext);
            convertView=inflater.inflate(mResource,parent,false);
            holder=new ViewHolder();
            holder._layout = convertView.findViewById(R.id.requestLayout);
            holder._bookingTime = convertView.findViewById(R.id.bookingTime);
            holder._userNameTextView = convertView.findViewById(R.id.userName);
            holder._ratingTextView = convertView.findViewById(R.id.rating);
            holder.acceptButton = convertView.findViewById(R.id.AcceptRequestButton);
            holder._rejectButton = convertView.findViewById(R.id.RejectRequestButton);

            holder._rejectButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(mContext, holder._rejectButton.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });

            holder.acceptButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(mContext, holder.acceptButton.getText().toString(), Toast.LENGTH_SHORT).show();
                }
            });


            convertView.setTag(holder);

        }
        else{
            holder=(ViewHolder)convertView.getTag();

        }
        holder._bookingTime.setText(getItem(position).getBookingTime());
        if(!getItem(position).getUserName().equals("")){

            holder._userNameTextView.setText(getItem(position).getUserName());
        }
        if(!getItem(position).getRating().equals("")){
            holder._ratingTextView.setText(getItem(position).getRating());
        }
        return  convertView;
    }

}

主 xml 中的 ListView:

<ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:id="@+id/AllRequestListView">

    </ListView>

列表视图 requestlayout.xml 的资源布局:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/requestLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bookingTime"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/bookingTime"
        android:text="Temp Name"
        android:id="@+id/userName"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/userName"
        android:text="No Rating"
        android:id="@+id/rating"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/AcceptRequestButton"
        android:focusable="false"
        android:layout_below="@+id/rating"
        android:text="Accept"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/RejectRequestButton"
        android:layout_below="@+id/AcceptRequestButton"
        android:focusable="false"
        android:text="Reject"
        />

</RelativeLayout>
于 2018-01-13T05:56:10.833 回答
0

在 getview 方法中,将侦听器放在检查视图之外..尝试遵循这个..它在我的情况下有效..如何增加或减少 listview 每一行中edittext的值?

于 2015-08-28T07:56:54.767 回答
0

我发现

final Button yourButton = (Button)view.findViewById(R.id.your_button);
yourButton.setFocusable(false);
yourButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        ...///);

可以解决问题。如果您想在单击按钮时获取一些数据,使用标签很有帮助。这里按钮被声明为final,因为它将在内部类中使用。

于 2018-03-29T12:13:24.200 回答
0

对于科特林用户

如果您尝试通过按钮 onClickListener 启动活动,请在 getView(...) 方法中:

   myButton.setOnClickListener{
        val intent = Intent(this@CurrentActivity, SecondActivity::class.java)
        startActivity(intent)
   }

为“this”传递正确的指针

于 2018-08-06T22:10:26.940 回答