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

时间:2018-02-01 21:41:34

标签: android mvvm observable android-livedata

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

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

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

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

不接受大写评论

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

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);
    }

}

并执行我的视图模型:

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 */
    }
};

1 个答案:

答案 0 :(得分:0)

如果您想使用自己的PropertyChangeRegistry,我很确定您需要覆盖BaseObservable的{​​{1}} / addOnPropertyChangedCallback

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);字段。