【问题标题】:Android: saving checkbox-state of ListView items into instances of custom objectAndroid:将 ListView 项目的复选框状态保存到自定义对象的实例中
【发布时间】:2018-04-27 18:02:26
【问题描述】:

我的最终目标是在 SQLite 表中为 ListView 的每个项目存储一个自定义对象“Place”的实例。

第 1 步将简单地提取 Place 对象,我能够使用适配器获取 Place 的各种成员变量,但我已经尝试了几天来获取列表视图中每个复选框的选中状态,但无法获取它工作,应该没那么难。我已经尝试了所有我能想到的听众,但是当我选中一个框时它没有注册。最后,我确实需要将检查状态作为整数(1 或 0)而不是布尔值,以便将其保存到数据库中。下面我发布了我一直在开发的测试应用程序版本的代码,所以我不再搞砸真实的东西,我真的很感激任何帮助!

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:onClick="itemClicked"
    android:paddingRight="8dp"/>

<TextView
    android:id="@+id/place_nameandaddress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:gravity="center_vertical"
    android:minHeight="?android:listPreferredItemHeight"/>

</LinearLayout>


public class Place {

String mName;
String mAddress;
double mLatitude;
double mLongitude;
public int mCheckedStatus;

public Place(String name, String address, double latitude, double longitude, int integer){
    mName = name;
    mAddress = address;
    mLatitude = latitude;
    mLongitude = longitude;
    mCheckedStatus = integer;
}

public String getName() {
    return  mName;
}

public String getAddress() {
    return  mAddress;
}

public double getLatitude() {
    return  mLatitude;
}

public double getLongitude() {
    return  mLongitude;
}

public int getCheckedStatus(){ return mCheckedStatus;}

public void setCheckedStatus(int integer){
    mCheckedStatus = integer;
}

public boolean isSelected() {
    if (mCheckedStatus ==1) {
        return true;
    } else {
        return false;
    }
 }
}

public class PlaceAdapter extends ArrayAdapter<Place> {

public PlaceAdapter(@NonNull Context context, int resource, ArrayList<Place> places) {
    super(context, 0, places);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.place_item, parent, false);
    }

    Place currentPlace = getItem(position);

    TextView placeview = convertView.findViewById(R.id.place_nameandaddress);

// remove commas so can later use commas to separate items of the arraylist
    String name = currentPlace.getName().replace(",", "");
    String address = currentPlace.getAddress().replace(",", "");
    placeview.setText(name + " at " + address);


    double latitude = currentPlace.getLatitude();
    double longitude = currentPlace.getLongitude();
    Log.i("Debugging: Lat and Long", String.valueOf(longitude) + String.valueOf(latitude));

    CheckBox checkbox = convertView.findViewById(R.id.checkbox);
      if (currentPlace.isSelected()) {
          checkbox.setChecked(true);
      } else {
          checkbox.setChecked(false);
      }

        return convertView;

    }
}




public class MainActivity extends AppCompatActivity {

ListView listView;
Uri mIntentUri;
CheckBox checkBox;
int checkboxstatus;
Place currentplace;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<Place> places = new ArrayList<Place>();
    places.add(new Place("name1", "address1", 12.3, 23.3, 0));
    places.add(new Place("name2", "address2", 12.4, 23.4, 0));
    places.add(new Place("name3", "address3", 12.5, 23.5, 0));
    places.add(new Place("name4", "address4", 12.6, 23.6, 0));
    places.add(new Place("name5", "address5", 12.7, 23.7, 0));
    listView = findViewById(R.id.listview);
    PlaceAdapter placeAdapter = new PlaceAdapter(this, 0, places);
    listView.setAdapter(placeAdapter);
}

//get user input from editor and saves value entered into new or edited goal into database
    public void saveGoal() {

       PlaceAdapter allplacesAdapter = (PlaceAdapter) listView.getAdapter();

        ArrayList<String> places = new ArrayList<>();
        double latitude = 0;
        double longitude = 0;

        for ( int i=0; i < allplacesAdapter.getCount();i++) {
            currentplace = allplacesAdapter.getItem(i);
            String name = currentplace.getName().replace(",","");
            String address = currentplace.getAddress().replace(",","");

            View view =  LayoutInflater.from(this).inflate(R.layout.place_item, listView, false);
            checkBox = view.findViewById(R.id.checkbox);
            if (checkBox.isChecked()){
                currentplace.setCheckedStatus(1);
            }
                else {
                currentplace.setCheckedStatus(0);
            }

            checkboxstatus = currentplace.getCheckedStatus();                
            latitude = currentplace.getLatitude();
            longitude = currentplace.getLongitude();
            String placeString = name + "," + address + "," + latitude + "," + longitude + "," + checkboxstatus;
            Log.i("Debugging: placeString",placeString);
            places.add(placeString);
        }
        String arrayString = android.text.TextUtils.join(";", places);
        Log.i("Debugging: arrayString",arrayString);

        if (TextUtils.isEmpty(arrayString)) {
            return;
        }
        ContentValues contentValues = new ContentValues();
        contentValues.put(GoalContract.GoalEntry.COLUMN_PLACE, arrayString);
        Log.i("Debugging:contentValues", contentValues.toString());

        // informs user of whether values entered into the GoalEditor were saved or there was an error
        //if (mIntentUri == null) {
            Uri newUri = getContentResolver().insert(GoalContract.GoalEntry.FINAL_CONTENT_URI, contentValues);
            if (newUri == null) {
                Toast.makeText(this, "Error with saving goal", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Goal successfully saved", Toast.LENGTH_LONG).show();
            }
    }

// sets options menu if GoalEditor screen
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_goaleditor, menu);
    return true;
}

// determines what should happen if the different menu options in the GoalEditor screen are selected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_save:
            saveGoal();
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

【问题讨论】:

    标签: android listview checkbox


    【解决方案1】:

    试试下面的适配器:

        public class PlaceAdapter extends ArrayAdapter<Place> {
    
        public PlaceAdapter(@NonNull Context context, int resource, ArrayList<Place> places) {
            super(context, 0, places);
        }
    
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.place_item, parent, false);
            }
    
            Place currentPlace = getItem(position);
    
            TextView placeview = convertView.findViewById(R.id.place_nameandaddress);
    
    // remove commas so can later use commas to separate items of the arraylist
            String name = currentPlace.getName().replace(",", "");
            String address = currentPlace.getAddress().replace(",", "");
            placeview.setText(name + " at " + address);
    
    
            double latitude = currentPlace.getLatitude();
            double longitude = currentPlace.getLongitude();
            Log.i("Debugging: Lat and Long", String.valueOf(longitude) + String.valueOf(latitude));
    
            CheckBox checkbox = convertView.findViewById(R.id.checkbox);
            checkbox.setChecked(currentPlace.isSelected());
            checkbox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    CheckBox cb = (CheckBox)view;
                    int position = (int)cb.getTag();
                    Place currentPlace = getItem(position);
                    if(cb.isChecked()) currentPlace.setCheckedStatus(1); else currentPlace.setCheckedStatus(0);
                }
            });
    
            checkbox.setTag(position);
            return convertView;
    
        }
    }
    

    并移动“ArrayList places = new ArrayList();”到 onCreate() 之外。复选框状态在数组列表中。

    希望有帮助!

    【讨论】:

    • 啊哈,谢谢。这帮助我摆脱困境。它仍然在为新视图回收复选框状态,但我设法解决了这个问题。谢谢!
    猜你喜欢
    • 2011-03-14
    • 2011-03-14
    • 2020-10-06
    • 2011-08-20
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多