簡體   English   中英

如何在單擊按鈕時從ArrayList和ArrayAdapter中刪除所選項目?

[英]How Do I Remove Selected Item From ArrayList and ArrayAdapter On Button Click?

我有一個帶有自定義列表布局的ListView。 我為此使用ArrayList和ArrayAdapter。 我很難從arraylist中刪除選定的項目。 我不確定要我做錯了。 這是我擁有的一個數組列表的示例:

項目A

項目B

項目C

項目D

假設我選擇了按鈕C,然后單擊標簽為“刪除”的項目C,然后從列表中刪除了項目C。 我該如何完成? 目前,我的代碼僅刪除索引0上的項目。我希望刪除選定的項目索引。

這是我的密碼...

Java類:

public class MainActivity extends AppCompatActivity {

ListView lstVw;
Button addBtn, removeBtn, clearListBtn;

ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
int getPosition = 0;

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

    lstVw = findViewById(R.id.lstView);
    addBtn = findViewById(R.id.add_item_btn);
    removeBtn = findViewById(R.id.remove_item_btn);
    clearListBtn = findViewById(R.id.clear_list_btn);

    arrayList = new ArrayList<>();
    adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, R.id.item_tv, arrayList);
    lstVw.setAdapter(adapter);



    lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String getItem = adapter.getItem(position);
            getPosition = Integer.parseInt(getItem);
        }
    });

    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
            adb.setTitle("Enter Item Name");
            final EditText itemTxt = new EditText(MainActivity.this);
            itemTxt.setText(getString(R.string.default_item_name_value));
            itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
            adb.setView(itemTxt);

            adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String getItem = itemTxt.getText().toString();

                    Set<String> s = new LinkedHashSet<>(arrayList);
                    if (s.contains(getItem)) {
                        arrayList.clear();
                        arrayList.addAll(s);
                        Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
                    } else {
                        arrayList.add(getItem);
                        adapter.notifyDataSetChanged();
                    }
                }
            });

            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            adb.create();
            adb.show();
        }
    });

    clearListBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!arrayList.isEmpty()) {
                arrayList.clear();
                adapter.notifyDataSetChanged();
            }
        }
    });


    removeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String getItem = arrayList.get(getPosition);
            arrayList.remove(getItem);
            adapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
        }
    });

}

}

主要XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="650dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="650dp">

        <ListView
            android:id="@+id/lstView"
            android:layout_width="match_parent"
            android:layout_height="650dp"
            tools:ignore="NestedScrolling" />

    </RelativeLayout>
</ScrollView>

<include layout="@layout/action_buttons"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"/>

動作按鈕XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center|top">

<Button
    android:id="@+id/add_item_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:textAllCaps="false"
    android:text="@string/add_item_text"
    android:textSize="14sp"
    android:textStyle="bold"
    android:textColor="@android:color/black"/>

<Button
    android:id="@+id/remove_item_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toEndOf="@id/add_item_btn"
    android:textAllCaps="false"
    android:text="Remove Item"
    android:textColor="@android:color/black"
    android:textSize="14sp"
    android:textStyle="bold"/>

<Button
    android:id="@+id/clear_list_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_toEndOf="@id/remove_item_btn"
    android:textAllCaps="false"
    android:text="@string/clear_list_text"
    android:textSize="14sp"
    android:textStyle="bold"
    android:textColor="@android:color/black"/>

我的自定義列表布局XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


<TextView
    android:id="@+id/item_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:textSize="20sp"
    android:textColor="@android:color/black"/>

</ScrollView>

感謝您的幫助! 謝謝!

在我看來,您的int getPosition = 0; 變量沒有更新為您的新職位。 在您的點擊監聽器上,您正在嘗試將所選項目的值解析為Integer,也許您可​​以嘗試僅使用當前位置進行更新?

lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        getPosition = position;
    }
});

編輯:

你可以這樣:

創建一個接口,您的活動將實現該接口,適配器將使用該接口來通知職位變更:

public interface PositionChangeListener {
    void onPositionChanged(int newPosition);
}

創建一個自定義適配器:

public class CustomAdapterView extends BaseAdapter {

private Context context;
private PositionChangeListener listener;
private ArrayList<String> items;

public CustomAdapterView(Context context, ArrayList<String> items, PositionChangeListener listener) {
    this.context = context;
    this.items = items;
    this.listener = listener;
}

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

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

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;

    if (convertView == null) {
        convertView = LayoutInflater.from(context).inflate( R.layout.item_list, null);
        viewHolder = new ViewHolder();
        viewHolder.txt = convertView.findViewById(R.id.item_tv);
        viewHolder.txt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onPositionChanged(position);
            }
        });
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.txt.setText(items.get(position));
    return convertView;
}

private class ViewHolder {
    TextView txt;
}

}

現在在您的活動中:

public class MainActivity extends AppCompatActivity implements PositionChangeListener{

ListView lstVw;
Button addBtn, removeBtn, clearListBtn;

ArrayList<String> arrayList;
BaseAdapter adapter;
int getPosition = 0;

@Override
public void onPositionChanged(int newPosition) {
    getPosition = newPosition;
}

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

    lstVw = findViewById(R.id.lstView);
    addBtn = findViewById(R.id.add_item_btn);
    removeBtn = findViewById(R.id.remove_item_btn);
    clearListBtn = findViewById(R.id.clear_list_btn);

    arrayList = new ArrayList<>();
    adapter = new CustomAdapterView(this, arrayList, this);
    lstVw.setAdapter(adapter);

    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
            adb.setTitle("Enter Item Name");
            final EditText itemTxt = new EditText(MainActivity.this);
            itemTxt.setText("default item name");
            itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
            adb.setView(itemTxt);

            adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String getItem = itemTxt.getText().toString();

                    Set<String> s = new LinkedHashSet<>(arrayList);
                    if (s.contains(getItem)) {
                        arrayList.clear();
                        arrayList.addAll(s);
                        Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
                    } else {
                        arrayList.add(getItem);
                        adapter.notifyDataSetChanged();
                    }
                }
            });

            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });

            adb.create();
            adb.show();
        }
    });

    clearListBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!arrayList.isEmpty()) {
                arrayList.clear();
                adapter.notifyDataSetChanged();
            }
        }
    });


    removeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String getItem = arrayList.get(getPosition);
            arrayList.remove(getItem);
            adapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
        }
    });

}

}

removeBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String getItem = arrayList.get(getPosition);
        arrayList.remove(getItem);
        adapter.notifyDataSetChanged();
        Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
    }
});

您從哪里獲得此getPosition?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM