I'm using a relative layout in Android, and when adding a view to the bottom of the screen the view is placed lower than the actual bottom of the screen, where the user cant actualy see it.

view.setY(container.getBottom()-view.getHeight());
container.addView(view);    

container is a RelativeLayout. i have also tried to use container.getHeight() which gave me the same result, and all the other solutions i found where using the xml file, which doesnt work for me since i need to add the view dynamically in a random position above the bottom of the screen, meaning

view.setY(container.getHeight()-Common.random.nextFloat()*100-view.getHieght());

this is the XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout"
    tools:context="il.co.ovalley.dashvsponypolice.app.MainActivity">
</RelativeLayout>

and the View im trying to add:

public class GameView extends ImageView{
  public GameView(RelativeLayout container) {
      super(container.getContext());
      m_container=container;
      container.addView(this);
  }
}

public class Cop extends GameView {
  public Cop(RelativeLayout container) {
    super(container);
    m_isShooting=false;
    m_LoadingTime=10;
    m_isLoading=false;
    m_xSpeed=1.5f;
    setY(container.getHeight()-Common.random.nextFloat()*100-getHeight()/*-getPaddingBottom()*/);
    float x=(Common.random.nextFloat()*m_container.getWidth());
    setX(x);
    drwableState=0;
    changeDirection();
 }

I have tested that on different versions of android and screen sizes and got the same result. so far, the only solution I found was subtracting an arbitrary int from the container's height which seems ok on one device and hope for the best for the others, I'm sure there is a better solution.


thnx

有帮助吗?

解决方案

Why don't you just place the view at the bottom of the screen with ALIGN_PARENT_BOTTOM and then apply a random padding?

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

view.setPadding(0, 0, 0, randomValue);  // left, top, right, bottom

container.addView(view, params);

All this calculating with the view.getHeight() is not good. Doing it like this works without you having to manage any of that yourself.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top