I am trying to add some radio button into a card view. Here's my code:
MainActivity.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. 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. Then I parse the LinearLayout to the loadAnswer() function, and here's the rest:
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. You can do it by creating a LinearLayout inside the CardView to add custom widget programmatically inside the CardView.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.