在微调器中使用LiveData

问题描述 投票:0回答:1

我在android中较新。我在项目中使用会议室数据库,AndroidViewModel和LiveDate。我的项目中有一个模型“ Receipt”,我有一个名为“ AddReceiptActivity”的活动,该活动中有一个微调器以显示并选择“放置”。还有另一个用于存储地点的地方模型。如何在Spinner中显示放置表的(模型)值以进行选择。这是我的地方实体

@Entity
public class Place implements Serializable {
@PrimaryKey(autoGenerate = true)
private Integer placeId;
private String placeName;

public Place(String placeName, Boolean removed) {
    this.placeName = placeName;
    this.removed = removed;
}

public Integer getPlaceId() {
    return placeId;
}

public void setPlaceId(Integer placeId) {
    this.placeId = placeId;
}

public String getPlaceName() {
    return placeName;
}

public void setPlaceName(String placeName) {
    this.placeName = placeName;
}
}

这是我的ViewModel

public class AddReceiptViewModel extends AndroidViewModel {
DataBase database;

public AddReceiptViewModel(@NonNull Application application) {
    super(application);
    database = DataBase.getDataBase(this.getApplication());
}

public void addRceipt(final Receipt receipt) {
    new AddAsyncTask(database).execute(receipt);
}

private static class AddAsyncTask extends AsyncTask<Receipt, Void, Void> {
    DataBase db;

    public AddAsyncTask(DataBase db) {
        this.db = db;
    }

    @Override
    protected Void doInBackground(Receipt... receipts) {
        db.receiptDao().add(receipts[0]);
        return null;
    }
}
}

现在我不知道如何在Activity中将数据从模型设置为Spinner。

     AddReceiptViewModel addReceiptViewModel = ViewModelProviders.of(this).get(AddReceiptViewModel.class);

     Spinner spinner = findViewById(R.id.spinnerLoadingPlace);
android mvvm android-room android-livedata
1个回答
0
投票

我假设您有一个清单是商店清单。

比方说List<Place> places = new ArrayList<>();

首先,您应该为Place模型的ovverride toString方法将每个地点的名称放入微调框。

@ovverride
public String toString(){
 return this.placeName;
}

在您的活动课程中,您将使用此功能将列表放入微调器中;

public void setList(){
ArrayAdapter<Place> adapter =
                new ArrayAdapter<Place>(getApplicationContext(),  android.R.layout.simple_spinner_dropdown_item, places);
        adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);
}

最后,您可以获得选定的项目;

Place selectedPlace = (Place) spinner.getSelectedItem();
© www.soinside.com 2019 - 2024. All rights reserved.