0

我想知道从 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 + ")");
}

}

4

1 回答 1

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()在适配器中创建一个方法。

于 2013-01-12T22:43:36.893 回答