ListView中的按钮setOnClickListener

时间:2015-08-17 12:49:46

标签: java android android-fragments android-listview

我正在尝试在listview中获取按钮的onclick事件,但它无法正常工作

fragment_contact.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="404dp"
    android:layout_weight="0.64"
    android:orientation="horizontal"
    android:paddingBottom="40dip" >

    <ListView
        android:id="@+id/contactlistview"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="fill"
        android:layout_weight="10"
        android:textSize="5pt"
        android:visibility="visible" />

</LinearLayout>

fragment_contact_content.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1">

    <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="New Button"
       android:id="@+id/btn_edit_contact"
       android:layout_gravity="right" />

</LinearLayout>

FragmentContact.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_contact, container, false);

    ListAdapter adapter_contact = new SimpleAdapter(
                    getActivity(), allcontact,
                    R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
                    new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});

    listview_contact = (ListView) view.findViewById(R.id.contactlistview);
    listview_contact.setItemsCanFocus(true);
    listview_contact.setAdapter(adapter_contact);

    Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
    btn_edit_contact.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("Do something");
        }
    });

    return view;
}

我也尝试过膨胀 fragment_contact_content.xml ,但该按钮仍无效。

2 个答案:

答案 0 :(得分:1)

使用自定义适配器并在getView中编写代码

public class MealAdapter extends BaseAdapter{
    private int  mHour, mMinute;
     int minutes,hour;
       String strtime;
    customButtonListener customListner; 
    private Context context;
    private List<Meal> rowItems;

    public MealAdapter(Context context, List<Meal> rowItems) {

        this.context = context;
        this.rowItems = rowItems;
    }

     @Override
     public int getCount() {
      return rowItems.size();
     }

     @Override
     public Object getItem(int position) {
      return rowItems.get(position);
     }

     @Override
     public long getItemId(int position) {
      return rowItems.indexOf(getItem(position));
     }
    private class OptionHolder
    {

        ImageButton btn_time;
        ImageButton btn_delete;
    }


    @Override
    public View getView(final int position,  View convertView, final ViewGroup parent) {
        // TODO Auto-generated method stub
         final OptionHolder holder;


         if (convertView == null) 
          {
             LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

           convertView = mInflater.inflate(R.layout.meal_list_item, null);
           holder = new OptionHolder();

           holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
           holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);

           convertView.setTag(holder);


           }
          else
          {
              holder = (OptionHolder) convertView.getTag();
          }
         final Meal row_pos=rowItems.get(position);
           row_pos.setMeal("");
           row_pos.setDetail("");
           holder.ed_meal.setText(row_pos.getMeal());
           holder.ed_detail.setText(row_pos.getDetail());
           holder.ed_time.setText(row_pos.getTime());

       holder.btn_time.setOnClickListener(new OnClickListener() {

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

            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // Launch Time Picker Dialog
            TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
                    new TimePickerDialog.OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker view, int hourOfDay,
                        int minute) {
                    // Display Selected time in textbox
                    strtime=(hourOfDay + ":" + minute);

                    row_pos.setTime(strtime);

                    row_pos.setMunite(minute);
                    row_pos.setHour(hourOfDay);
                    holder.ed_time.setText(row_pos.getTime());
                    }
            }, mHour, mMinute, false);
    tpd.show();

    }
    });
       holder.btn_delete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (customListner != null) {  
                customListner.onButtonClickListner(position,row_pos);  
            }  
        }
    });

          return convertView;
}
     public interface customButtonListener {  
            public void onButtonClickListner(int position,Meal row_pos);  
        }  
     public void setCustomButtonListner(customButtonListener listener) {  
            this.customListner = listener;  
        }  

}
`

答案 1 :(得分:0)

您无法直接在onCreateView中获取Listview单元格的Button事件。你必须为此制作CustomAdapter类。

您将需要创建一个Custom ArrayAdapter类,您将使用该类来扩充xml布局,以及处理按钮和单击事件。

public class MyCustomAdapter extends BaseAdapter implements ListAdapter { 
private ArrayList<String> list = new ArrayList<String>(); 
private Context context; 

public MyCustomAdapter(ArrayList<String> list, Context context) { 
    this.list = list; 
    this.context = context; 
} 

@Override
public int getCount() { 
    return list.size(); 
} 

@Override
public Object getItem(int pos) { 
    return list.get(pos); 
} 

@Override
public long getItemId(int pos) { 
    return list.get(pos).getId();
    //just return 0 if your list items do not have an Id variable.
} 

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
        view = inflater.inflate(R.layout.fragment_contact_content, null);
    } 

    //Handle button and add onClickListener
    Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);

    editBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            //some other task
            notifyDataSetChanged();
        }
    });

    return view; 
} 
}

最后,在您的活动中,您可以实例化自定义ArrayAdapter类并将其设置为listview

public class MyActivity extends Activity { 

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

    //generate list
    ArrayList<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");

    //instantiate custom adapter
    MyCustomAdapter adapter = new MyCustomAdapter(list, this);

    //handle listview and assign adapter
    ListView lView = (ListView)findViewById(R.id.my_listview);
    lView.setAdapter(adapter);
}

您可以参考以下链接:http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/

只需处理getview中的点击监听器,您可以使用findviewbyid找到该按钮

我希望它有所帮助!