【发布时间】:2014-05-07 10:09:27
【问题描述】:
我正在尝试为 Android 创建一个纸牌游戏,但我遇到了一个令人困惑的问题。 我有一个名为 CardBG 的自定义视图,它从 ViewFlipper 类扩展而来,这样我就可以翻转卡片并显示正面和背面。这很好用。 但是我需要在卡片中添加一些其他的东西,例如文本字段。所以我创建了一个视图组,相信我可以简单地向它添加视图。将此 ViewGroup 添加到我的 Activity 不会产生任何结果。 我究竟做错了什么?这是一个错误的方法吗? 我也尝试过让 Card 扩展一个布局类,例如 RelativeLayout,但它给了我相同的结果。
这是相关代码,添加卡片必须动态完成,所以没有xml恶作剧:
TestActivity.java
public class TestActivity extends Activity {
RelativeLayout menuLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
menuLayout = (RelativeLayout) findViewById(R.id.layout_menu);
Card c = new Card(this, null);
c.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
menuLayout.addView(c);
}
}
Card.java
public class Card extends ViewGroup{
CardBG background;
TextView text1;
public Card(Context context, AttributeSet attrs) {
super(context, attrs);
Log.w("Card", "Constructor");
background = new CardBG(context, null);
background.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.addView(background);
}
(protected void onLayout is also in this file, but i do nothing in that method except calling super.onLayout)
}
CardBG.java
public class CardBG extends ViewFlipper{
ImageView blue;
ImageView red;
public CardBG(Context context, AttributeSet attrs) {
super(context, attrs);
Log.w("CardBG", "Constructor");
blue = new ImageView(context);
blue.setImageResource(R.drawable.card_blue);
blue.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.addView(blue);
red = new ImageView(context);
red.setImageResource(R.drawable.card_red);
red.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.addView(red);
//from here on out there are only onclick listener to test the flipping animations
}
【问题讨论】:
-
怎么办?在 onLayout 中使用 setLayoutParams() 只会给出一堆错误/警告。你能给我一个例子吗?编辑:反对票是怎么回事?这是一个简单明了的问题。
-
使用 xml 布局和 LayoutInflater
标签: android android-custom-view viewgroup