簡體   English   中英

Android:將ListView項的復選框狀態保存到自定義對象的實例中

[英]Android: saving checkbox-state of ListView items into instances of custom object

我的最終目標是在SQLite表中為ListView的每個項目存儲自定義對象“ Place”的實例。

第1步將簡單地提取Place對象,並且我能夠使用適配器來獲取Place的各種成員變量,但是我已經嘗試了幾天,以獲取listview中每個復選框的選中狀態,但無法使其正常工作,並且應該沒有那么難。 我已經嘗試過我能想到的每個偵聽器,但是當我選中一個框時,它並沒有注冊。 最后,我確實需要檢查狀態為整數(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);
  }
}

嘗試以下適配器:

    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位置= new ArrayList();” 到onCreate()之外。 復選框狀態在陣列列表中。

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM