Android Linear Layout - How to Keep Element At Bottom Of View?

前端 未结 8 1488
悲哀的现实
悲哀的现实 2020-12-08 01:50

I have a TextView which I want to pin at the bottom of a landscape activity that is using LinearLayout with vertically arranged elements.

8条回答
  •  醉梦人生
    2020-12-08 02:09

    Update: I still get upvotes on this question, which is still the accepted answer and which I think I answered poorly. In the spirit of making sure the best info is out there, I have decided to update this answer.

    In modern Android I would use ConstraintLayout to do this. It is more performant and straightforward.

    
       
       
          ...other attributes elided... />
    
       ...etc for other views that should be aligned top to bottom...
    
       
    

    If you don't want to use a ConstraintLayout, using a LinearLayout with an expanding view is a straightforward and great way to handle taking up the extra space (see the answer by @Matthew Wills). If you don't want to expand the background of any of the Views above the bottom view, you can add an invisible View to take up the space.

    The answer I originally gave works but is inefficient. Inefficiency may not be a big deal for a single top level layout, but it would be a terrible implementation in a ListView or RecyclerView, and there just isn't any reason to do it since there are better ways to do it that are roughly the same level of effort and complexity if not simpler.

    Take the TextView out of the LinearLayout, then put the LinearLayout and the TextView inside a RelativeLayout. Add the attribute android:layout_alignParentBottom="true" to the TextView. With all the namespace and other attributes except for the above attribute elided:

    
      
        
      
      
    
    

提交回复
热议问题