purpule
purpule

Reputation: 116

addView method does not display new view

I want to add a new view to a FrameLayout, but it does only work "sometimes". For example: I have set an OnClickListener to my layout (inside the onCreate-method of the activity) which adds a new view to the layout (this works). In the run-method of the activity i am using exactly the same code to add such a view, but the view does not show up. I don't know why...

Here is some code:

OnClickListener, which adds a new view to the layout and the view actually shows up. layout is the FrameLayout, obstacles is an object-list.

layout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        obstacles.add(new Obstacle(getBaseContext(), 0, (int) ((scale * 570) / 8), scale));
        layout.addView(obstacles.get(obstacles.size() - 1).view);

    }
});

if statement IS true, the new view is not being displayed, but the size of obstacles and the layout's childcount increase both by 1

if(checkForNew()){
    obstacles.add(new Obstacle(getBaseContext(), 0, (int) ((scale * 570) / 8), scale));
    layout.addView(obstacles.get(obstacles.size() - 1).view);
}

Constructor of Obstacle

public Obstacle(Context con, int left, int top, float scale) {
    view = new ImageView(con);
    view.setBackgroundColor(Color.rgb(0, 0, 0));
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams((int)(scale*150), (int)(scale*20));
    params.setMargins(left,top,0,0);
    view.setLayoutParams(params);
    view.setMaxWidth(view.getLayoutParams().width);
    view.setMaxHeight(view.getLayoutParams().height);
}

This is moving the views:

public void Move( View view, float speed, float scale){
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(view.getWidth(), view.getHeight());
    params.setMargins(view.getLeft(), view.getTop() - (int) (scale * -speed), 0, 0);
    view.setLayoutParams(params);
}

Upvotes: 0

Views: 411

Answers (1)

David Medenjak
David Medenjak

Reputation: 34532

This is a FrameLayout and views will be on top of each other.

You do not seem to be changing the scale anywhere, and your margin is always fixed with 0, (scale * someValue)

You need to apply a different scale and/or use different top/left parameters for the views you add.

Upvotes: 1

Related Questions