在Android中使用自定义适配器刷新ListView

时间:2016-02-10 07:46:27

标签: android listview baseadapter

我正在为ListView使用自定义适配器。每个ListView项都包含ImageButton,该项将删除该项。现在,我想在任何人点击ListView时刷新完整ImageButton。这该怎么做 ?

或者有没有检查ImageButton点击ListView onItemClickListener?我已经在自定义适配器中尝试过notifyDataSetChanged,但我找不到任何更改。

自定义项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:background="@color/lightish"
    android:orientation="vertical"
    android:padding="10dp" >

    <ImageButton
        android:id="@+id/imgDelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:layout_marginBottom="-20dp"
        android:background="@android:color/transparent"
        android:contentDescription="@string/app_name"
        android:src="@drawable/ic_delete" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:textSize="20sp" />

</LinearLayout>

自定义适配器java:

public class MyAddressesAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater = null;

    View vi;
    HashMap<String, String> address;

    public MyAddressesAdapter(Activity a,
            ArrayList<HashMap<String, String>> arlData) {

        activity = a;
        data = arlData;

        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, final View convertView, ViewGroup parent) {
        vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.my_address_view, parent, false);

        final TextView tvName = (TextView) vi.findViewById(R.id.tvName);

        address = new HashMap<String, String>();
        address = data.get(position);

        tvName.setText(address.get("PersonName"));

        return vi;
    }

在主要活动java中:

myAddressesAdapter = new MyAddressesAdapter(
                                    getActivity(), addressList);
                            lvMyAddresses.setAdapter(myAddressesAdapter);

1 个答案:

答案 0 :(得分:0)

将代码放入适配器

中的getview方法
imageButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               //your code here

               data.remove(position);
               notifyDataSetChanged();

           }
       });