gpt4 book ai didi

Android - 绑定(bind)(观察)对象属性的 MVVM 架构

转载 作者:行者123 更新时间:2023-12-03 10:42:40 25 4
gpt4 key购买 nike

我试图构建一个简单的场景:
我有卡片列表,并将它们显示为切换按钮。
如果按下按钮,则卡状态打开,如果再次按下按钮,它将关闭。我想在 MVVM 架构中使用 observable 来实现它。

但由于某种原因,监听 card.status 的可观察监听器不起作用,希望有人可以在这里帮助我......

我尝试使用 livedata 然后可观察,没有运气

下面是我的代码(*如果不清楚,请告诉我,我会说清楚:))

不要接受大写的评论

所以,我有一个简单的卡片类:

public class Card extends BaseObservable {
private int mValue;
private CardStatus mStatus;

private PropertyChangeRegistry registry = new PropertyChangeRegistry();

public Card(CardType item) {
mValue = item.getValue();
setmStatus(item.getStatus());
}

public int getmValue() { return mValue; }

@Bindable
public CardStatus getmStatus() { return mStatus; }
/* I WANT TO OBSERVE THIS PROPERTY */

public void setmStatus(CardStatus status) {
this.mStatus = status;
registry.notifyChange(this, BR.mStatus);
}
}

在我的模型类中,我声明了我的卡片对象(卡片列表):
public class GameBoard {

private final List<MutableLiveData<Card>> mCards = new ArrayList<>();

public GameBoard(int size, int noPlayer) {

/* ... bla ... */

// INIT THE LIST OF CARD RANDOMLY
List<CardType> cards = CardType.getShuffledCard().subList(0, (getBoardSize().getValue()/2));
for (CardType item : cards){
MutableLiveData<Card> card = new MutableLiveData<>();
card.setValue(new Card(item));
mCards.add(card);
mCards.add(card);
}

Collections.shuffle(mCards);
}

/* ... bla ... */

public LiveData<Card> getCard(Integer id) { return mCards.get(id); }

// TRIGGERED WHEN USER CLICK TOGGLE BUTTON IN VIEW
public void flipCard(Integer id){
Card card = mCards.get(id).getValue();
if(card.getmStatus() == CardStatus.CLOSE) card.setmStatus(CardStatus.OPEN);
else card.setmStatus(CardStatus.CLOSE);
}

}

并执行到我的 View 模型:
public class GameActivityVM extends AndroidViewModel implements ViewModel {

private final List<LiveData<Card>> mListCardsObservable = new ArrayList<>();

private final List<ObservableField<Card>> mListCards = new ArrayList<>();

private GameBoard mBoard;

public GameActivityVM(@NonNull Application application, Integer gridSize, Integer noPlayer) {
super(application);

mBoard = new GameBoard(gridSize, noPlayer);
/* ... bla ... */

// POPULATE THE CARD FROM MODEL TO BE OBSERVE BY VIEW THROUGH VIEW MODEL
for(int i=0; i<mBoard.getBoardSize().getValue(); i++){ mListCardsObservable.add(mBoard.getCard(i)); }

}

/**
* Expose the LiveData Projects query so the UI can observe it.
*/
public LiveData<Card> getListCardsObservable(Integer index) { return mListCardsObservable.get(index); }

public void setCard(Integer index, Card card) { mListCards.add(index, new ObservableField<>(card)); }
public ObservableField<Card> getCard(Integer index){ return mListCards.get(index); }

public void onClick(ToggleButton btn) {
Integer id = btn.getId();
mBoard.flipCard(id);

/* SO I TRY TO CHANGE PROPERTY OF CARD HERE - BUT IT DIDN'T GET OBSERVE */
if(mListCards.get(id).get().getmStatus() == CardStatus.CLOSE) mListCards.get(id).get().setmStatus(CardStatus.OPEN);
else mListCards.get(id).get().setmStatus(CardStatus.CLOSE);

}

public static class Factory extends ViewModelProvider.NewInstanceFactory { /* ... bla ... */ }

最后是我的观点:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

/* *** bla *** */

ActivityGameBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_game);
GameActivityVM.Factory factory = new GameActivityVM.Factory(app, size, player);
final GameActivityVM viewModel = ViewModelProviders.of(this, factory)
.get(GameActivityVM.class);

binding.setVm(viewModel);

subscribeToModel(viewModel);
viewModel.onCreate();

/* *** bla *** */

}

private void subscribeToModel(final GameActivityVM model) {
// OBSERVE BOARD LIVEDATA
observeBoard(model);
}

private void observeBoard(GameActivityVM viewModel){
// Update the list when the data changes
viewModel.getBoardSizeObservable().observe(this, size -> {
if (size == null) return;

// BUILD THE UI AND BUTTONS BASED ON CARD QTY (SIZE)
mGrids.removeAllViews();
Integer noColumn = 4;
ToggleButton btnCard;
LinearLayout linearLayout = null;
for(int i=0; i<(size); i++){
if(i%noColumn == 0){
linearLayout = new LinearLayout(this);
linearLayout.setPaddingRelative(3,3,3,3);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
mGrids.addView(linearLayout);
}
btnCard = new ToggleButton(this);
btnCard.setId(i);
btnCard.setForeground(getDrawable(R.drawable.ic_help_outline_black_24px));
btnCard.setForegroundGravity(Gravity.CENTER);
btnCard.setTextOff("");
btnCard.setTextOn("");
btnCard.setText("");
btnCard.setChecked(false);
btnCard.setLayoutParams(
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
200
)
);
btnCard.setOnClickListener((View v) -> viewModel.onClick((ToggleButton) v)); // WHEN BUTTON CLICK, FLIP CARD (CHANGE CARD STATUS)
linearLayout.addView(btnCard);

// REGISTER CARD OBSERVER FOR EACH INDIVIDUAL CARD/BUTTON
observeCard(i, viewModel);
}
});
}

private void observeCard(Integer index, GameActivityVM viewModel) {
// Update the list when the data changes
viewModel.getListCardsObservable(index).observe(this, cards -> {
if (cards == null) return;

// REGISTER CARD ON PROP CHANGE
cards.addOnPropertyChangedCallback(propertyChangeCallback);
viewModel.setCard(index, cards);
});
}

Observable.OnPropertyChangedCallback propertyChangeCallback = new Observable.OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int property) {
// MY CODE NEVER GET HERE - WHY T_T
Log.e("onPropertyChanged: %s", "" + property); /* <-- THIS WILL NEVER GET TRIGGERED */
}
};

最佳答案

如果您想使用自己的PropertyChangeRegistry ,我很确定您需要覆盖 BaseObservableaddOnPropertyChangedCallback/removeOnPropertyChangedCallback :

@Override
public void addOnPropertyChangedCallback(OnPropertyChangedCallback callback) {
registry.add(callback);
}

@Override
public void removeOnPropertyChangedCallback(OnPropertyChangedCallback callback) {
registry.remove(callback);
}

它不知道用你的 PropertyChangeRegistry否则回调。

但是,只有当您想使用自己的 PropertyChangeRegistry .

除非您有特定的理由不这样做,否则您应该利用 BaseObservable 的事实。管理 PropertyChangeRegistry给你的逻辑。你需要做的就是换掉你的 registry.notifyChange(this, BR.mStatus);对于 notifyPropertyChanged(BR.mStatus); .这样,您无需进行任何覆盖,并且可以摆脱您的 PropertyChangeRegistry field 。

关于Android - 绑定(bind)(观察)对象属性的 MVVM 架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com