how to get the bottom of a layout in android?

南楼画角 提交于 2019-12-24 00:05:39

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/23208263/how-to-get-the-bottom-of-a-layout-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!