Android - 将ImageView停靠在LinearLayout的底部

时间:2014-11-20 08:25:07

标签: android android-layout gridview imageview

我有一个Android应用,我正在尝试在代码中创建以下布局:

enter image description here

这是我到目前为止的代码:

public class MyLayout extends LinearLayout {

     private Context mContext;

     public MyLayout(Context context) {
         super(context);
         mContext = context;
         this.build();
     }

     private void build() {
         LinearLayout parent = new LinearLayout(mContext);
         parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
             LayoutParams.FILL_PARENT));

         GridView gridView = new GridView(this.mContext);
         gridView.setNumColumns(2);
         ViewGroup.LayoutParams params = new ViewGroup.MarginLayoutParams(
                 MarginLayoutParams.FILL_PARENT,
                 MarginLayoutParams.WRAP_CONTENT);
         gridView.setLayoutParams(params);
         parent.addView(gridView);

         addView(parent);
     }
}

如何添加ImageView以使其停靠在LinearLayout的底部?

2 个答案:

答案 0 :(得分:0)

您可以使用如下所示的xml布局,然后在onCreate方法中使用setContentView(R.layout.your_layout_name)加载它。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:weightSum="10" >

    <GridView 
        android:id="@+id/yourGridViewID"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="8" />

    <ImageView 
        android:id="@+id/yourImageViewID"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="2"/>

</LinearLayout>

答案 1 :(得分:-1)

参考此代码:

public class MyLayout extends LinearLayout {

 private Context mContext;
 private LinearLayout parent;
 public MyLayout(Context context) {
     super(context);
     mContext = context;
 parent = new LinearLayout(mContext);
     this.build();
 }

 private void build() {

     parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
         LayoutParams.FILL_PARENT));

     GridView gridView = new GridView(this.mContext);
     gridView.setNumColumns(2);
     ViewGroup.LayoutParams params = new ViewGroup.MarginLayoutParams(
             MarginLayoutParams.FILL_PARENT,
             MarginLayoutParams.WRAP_CONTENT);

     gridView.setLayoutParams(params);
     ImageView imageview = new ImageView(this.mContext);
     ViewGroup.LayoutParams params2 = new ViewGroup.MarginLayoutParams(
             MarginLayoutParams.FILL_PARENT,
             MarginLayoutParams.WRAP_CONTENT);
     params2.gravity = Gravity.BOTTOM;
     imageview.setLayout(params2);
     parent.addView(gridView);
     parent.addView(imageview);

     addView(parent);
 }
}