简体   繁体   English

如何在livedata观察者中向cardview添加视图

[英]How to add view to cardview inside livedata observer

I am trying to add some radio button into a card view.我正在尝试将一些单选按钮添加到卡片视图中。 Here's my code:这是我的代码:

MainActivity.java主活动.java

cardView = findViewById(R.id.card_view);
mGameViewModel.setUpGame().observe(this,this::loadRound);

private void loadRound(List<Smiley> smileys) {
    if (smileys == null) {
        return;
    }
    mAnswersView.loadAnswers(smileys, cardView);
    mGameViewModel.startNewGameRound();
}

AnswerView答案视图

public void loadAnswers(List<Smiley> smileys, CardView cardView) {
    if (smileys == null) {
        return;
    }
    removeAllViews();
    LayoutInflater inflater = LayoutInflater.from(getContext());

    for (Smiley smiley : smileys) {
        RadioButton button = (RadioButton) inflater.inflate(R.layout.answer_item, this, false);
        button.setText(smiley.getName());
        button.setTag(R.string.answer_tag, smiley.getCode());
        cardView.addView(button);
    }
}

But that doesn't seem to work.但这似乎不起作用。 Any idea please?请问有什么想法吗?

EDIT: The problem here is that the radio button i try to create doesn't show.编辑:这里的问题是我尝试创建的单选按钮没有显示。 I've already do some debugging and all of the methods are called until the addView method.我已经做了一些调试,所有的方法都被调用,直到 addView 方法。 But when i take a look on the device, there's no 'extended' view, in this case, radio button at all.但是当我查看设备时,没有“扩展”视图,在这种情况下,根本没有单选按钮。

So, i fixed the problem by using LinearLayout inside the CardView.所以,我通过在 CardView 中使用 LinearLayout 解决了这个问题。 Then I parse the LinearLayout to the loadAnswer() function, and here's the rest:然后我将 LinearLayout 解析为 loadAnswer() 函数,剩下的就是:

RadioButton button = (RadioButton) inflater.inflate(R.layout.answer_item, linearLayout, false);
button.setText(smiley.getName());
button.setTag(R.string.answer_tag, smiley.getCode());
linearLayout.addView(button);

From this case, I learnt that we can't directly addView to the CardView.从这个案例中,我了解到我们不能直接将View添加到CardView。 You can do it by creating a LinearLayout inside the CardView to add custom widget programmatically inside the CardView.您可以通过在 CardView 中创建 LinearLayout 以在 CardView 中以编程方式添加自定义小部件来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM