我創建了一個列表視圖demo.list已成功創建,圖像也被正確添加到右側。現在我想要當我點擊列表視圖中右側的交叉圖像時,那麼該行將被刪除。如何從Android的列表視圖中刪除行項目?
public class MainActivity extends Activity {
EditText editText;
Button Button,Button1;
ListView listView;
ArrayList<String> listItems;
BaseAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
// int pos = editText.getText().length();
//editText.setSelection(pos);
Button = (Button) findViewById(R.id.Button);
listView = (ListView) findViewById(R.id.listview);
//listView.setSelection(listView.getAdapter().getCount()-1);
listItems = new ArrayList<String>();
//listItems.add("First item");
//code to only set the simple text in the listview
//adapter = new ArrayAdapter<String>(this, R.layout., listItems);
//Here is the creation of new anonymous class,because we can not create subclass inside any method so we create anonymous class inside the on create method
adapter =new BaseAdapter()
{
@Override
public View getView(int arg0, View arg1, ViewGroup arg2)
{
// arg1 is the particular row position in list view weather the arg0 is the whole list view
// layout inflater for setting the text or an image on row in list view
LayoutInflater inflater = getLayoutInflater();
arg1 = inflater.inflate(R.layout.custom, null);
TextView textview = (TextView)arg1. findViewById(R.id.textView1);
textview.setText(listItems.get(arg0));
return arg1;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return listItems.size();
}
};
listView.setAdapter(adapter);
Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
// code to display the previous added text in front through edit text in
listView.setSelection(listView.getAdapter().getCount()-1);
//code to clear edit text after enter the text in list view
editText.getText().clear();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Toast.makeText(MainActivity.this, "Item has been added into your list", Toast.LENGTH_LONG)
.show();
}
});
}
}
刪除項目形式你的列表填充listview並調用'adapter.notifyDataSetChanged()' – Raghunandan 2014-09-25 07:03:44
我不理解你的問題,請簡要清楚。 – user3905549 2014-09-25 07:05:41
根據索引從'listItems'中刪除項目,然後在適配器上調用notifydatasetchanged來更新listview。做搜索stackoverflow你會發現類似的帖子 – Raghunandan 2014-09-25 07:12:01