To show only the chosen item in the ListView for Android, you can perform the following steps:
Here is some sample code to achieve this:
public class MyListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
MyAdapter adapter;
int selectedPosition = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_list);
listView = findViewById(R.id.listview);
adapter = new MyAdapter(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedPosition = position;
adapter.notifyDataSetChanged();
}
private class MyAdapter extends BaseAdapter {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return 10;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = getLayoutInflater().inflate(R.layout.list_item, parent, false);
if (position == selectedPosition) {
itemView.setVisibility(View.VISIBLE);
} else {
itemView.setVisibility(View.GONE);
}
return itemView;
}
}
}
In this example, we have a listview with 10 items and a custom adapter that inflates a list item layout. In the onItemClick listener, we store the selected position in the selectedPosition variable and call adapter.notifyDataSetChanged() to update the listview. In the adapter's getView() method, we check if the current position is equal to the selected position and show or hide the item accordingly.
Asked: 2022-07-22 11:00:00 +0000
Seen: 8 times
Last updated: Oct 18 '21