简体   繁体   中英

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

I have ListView with a custom list layout. I am using an ArrayList and ArrayAdapter for this. I am having a difficult time removing selected items from the arraylist. I am not sure want I am doing wrong. Here's an example of a arraylist that I have:

Item A

Item B

Item C

Item D

Let's say that I selected Item C next on button clicked labeled "Remove" I want Item C removed from the list. How do I accomplish this? Currently my code only removes the item on index 0. I want selected item index to be removed.

Here's my codes...

Java Class:

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();
        }
    });

}

}

Main 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"/>

Action Buttons 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"/>

My Custom List Layout 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>

I appreciate the help! Thanks!

It looks to me like your int getPosition = 0; variable is not getting updated with your new position. On your click listener you are trying to parse the value of your selected item to an Integer, maybe you could try simply updating with the current position instead?

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

Edit:

You could go with something like this:

Create an interface that your activity will implement and will be used by your adapter to notify a position change:

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

Create a custom adapter:

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;
}

}

And now in your activity:

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();
    }
});

From where are you getting this getPosition?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM