Skip to content

Instantly share code, notes, and snippets.

@Ephygtz
Created April 25, 2019 07:02
Show Gist options
  • Save Ephygtz/6445741f0677df742d9ce107d738f1e4 to your computer and use it in GitHub Desktop.
Save Ephygtz/6445741f0677df742d9ce107d738f1e4 to your computer and use it in GitHub Desktop.
public class RemoveSelectedListViewItem extends Activity {
// Declare view variables
ListView mListview;
// define array with data to display on listview
String[] mCoffeeCocktails = {
"Espresso",
"Short Latte",
"Cappuccino",
"Americano",
"Vanilla latte",
"Caramel Macchiato"
};
List<String> mCoffeeList;
ArrayAdapter<String> mArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assign variable to view
mListView = findViewById(R.id.listCocktails);
//convert array to list(List has a remove method)
mCoffeeList = new ArrayList<String>(Arrays.asList(mCoffeeCocktails));
//assign adapter to layout and data
mArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, mCoffeeList);
mListView.setAdapter(mArrayAdapter);
//set on long click listener on listView
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//remove selected item
mCoffeeList.remove(position);
mArrayAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Item Deleted", Toast.LENGTH_LONG).show();
return true;
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment