我想知道从ListView中删除TextView的最佳方法, 但我想从选项菜单中进行操作。 所以我点击“删除国家” - 它将等待,直到我将点击一个国家而不是删除被点击的国家。 我是编程新手。提前谢谢
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.omAddCountry:
Intent addCountryIntent = new Intent(MainActivity.this, AddCountryActivity.class);
startActivityForResult(addCountryIntent, 11);
break;
case R.id.omDeleteCountry:
break;
ListView正在使用SQLite,它从DB获取第一个视图,TextViews由适配器中的Vector添加。
public class CountryAdapter extends BaseAdapter {
private Context mContext;
protected Vector<Country> mVector;
protected SQLiteDatabase mDb;
public void setmContext(Context mContext){
this.mContext = mContext;
}
public CountryAdapter(Context mContext){
this.mContext = mContext;
mVector = new Vector<Country>();
CountryOpenHelper helper = new CountryOpenHelper(mContext);
mDb = helper.getWritableDatabase();
Cursor cursor = mDb.rawQuery("SELECT * FROM COUNTRIES", null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
}
do {
Country country = new Country();
country.setmCountryIndex(cursor.getInt(0));
country.setmCountryName(cursor.getString(2));
country.setmCountryTextSize(cursor.getInt(1));
country.setmCountryColor(cursor.getInt(3));
mVector.add(country);
} while (cursor.moveToNext());
}
public Vector<Country> getmVector() {
return mVector;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mVector.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if(convertView == null){
tv = new TextView(mContext);
}else{
tv = (TextView) convertView;
}
tv.setText(mVector.get(position).getmCountryName());
tv.setTextColor(mVector.get(position).getmCountryColor());
tv.setTextSize(mVector.get(position).getmCountryTextSize());
return tv;
}
public void ChangeColor(int newcolor, String name) {
mDb.execSQL("update COUNTRIES set color = " + newcolor + " where name = '" + name + "' " );
}
public void addCountry(int mId, String myCountry, int myColorNum){
mDb.execSQL("insert into countries values(" + mId + " , ' " + myCountry+"' , "+ myColorNum + ")");
}
}
答案 0 :(得分:2)
创建一个全局布尔值:
boolean isDeleting = false;
然后在onOptionsItemSelected()
中,执行:
case R.id.omDeleteCountry:
isDeleting = true;
break;
无论您实施onListItemClick()
:
@Override
public void onListItemClick (ListView listView,View view, int pos, long id)
{
if (isDeleting){
yourCustomAdapter.delete(pos)
yourCustomAdapter.notifyDataSetChanged();
isDeleting = false;
}
else {
//do other stuff
}
}
您必须在适配器中创建delete()
方法。