0

我有一个扩展 View 的 Ball 类。在里面我给出了一些特性并实现了 onTouchEvent(),所以我可以处理运动。我也使用 onDraw,所以我可以绘制球的位图。在我的活动类中,我创建了一个新布局,并将视图添加到其中以便显示。一切正常,除非我尝试在我的布局中添加更多球,但它们没有出现!总是显示第一个添加到布局中的球!这是活动类的 onCreate 代码:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.HORIZONTAL);
    int lHeight = LinearLayout.LayoutParams.WRAP_CONTENT;
    int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;

    Point point1 = new Point();
    point1.x = 50;
    point1.y = 20;
    Point point2 = new Point();
    point2.x = 100;
    point2.y = 20;
    Point point3 = new Point();
    point3.x = 150;
    point3.y = 20;

    ColorBall ball1 = new ColorBall(this,R.drawable.bol_groen, point1);
    ll.addView(ball1, new LinearLayout.LayoutParams(lHeight, lWidth));
    setContentView(ll);

    ColorBall ball2 = new ColorBall(this,R.drawable.bol_rood, point2);
    ll.addView(ball2, new LinearLayout.LayoutParams(lHeight, lWidth));
    setContentView(ll);

    ColorBall ball3 = new ColorBall(this,R.drawable.bol_blauw, point3);

    ll.addView(ball3, new LinearLayout.LayoutParams(lHeight, lWidth));
    setContentView(ll);        

}

可能是什么问题?我最后也只尝试了一个 setContentView()。我想我不能使用布局,所以我可以绘制自定义视图中的位图!我说得对吗?我是否应该更改我的代码并创建一个视图,并在其中创建一个包含我想要显示的所有球的数组,然后将此视图设置为从我的主要活动类中显示?(例如这个 setContentView(customview))。

4

1 回答 1

0

您调用setContentView了多次,而每个活动初始化预计只调用一次。

更新

您可以使用此布局 xml 代替您使用的编程方式吗?这只是为了 100% 确定要添加 ColorBalls 的容器是否正常。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/container"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" />

以防万一,这是将其包含在活动中的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_name_of_layout);

    LinearLayout container = (LinearLayout) findViewById(R.id.container);
    ..
    container.addView(ball1);
    container.addView(ball2);
    ..
}
于 2011-02-17T20:06:10.180 回答