繁体   English   中英

在Android中将ImageView添加到RelativeLayout

[英]Add ImageView to RelativeLayout in Android

因此,我在Activity以编程方式创建了ImageView
我想将此ImageView添加到我的RelativeLayout的底部。

这是我尝试的:

// creating new ImageView
ImageView shadowView = new ImageView (contextPara);
shadowView.SetBackgroundResource (Resource.Drawable.bottomBar_Shadow);
shadowView.SetScaleType (ImageView.ScaleType.FitXy);

// creating ImageView LayoutParams
WindowManagerLayoutParams imgViewLayoutParams = new WindowManagerLayoutParams ();
imgViewLayoutParams.Width = ViewGroup.LayoutParams.MatchParent;
imgViewLayoutParams.Height = (int)imgViewHeight;
imgViewLayoutParams.Gravity = GravityFlags.Bottom;

// Adding ImageView to RelativeLayout
listViewRelativeLayout.AddView (shadowView, imgViewLayoutParams);

我的问题是,这会将ImageView添加到RelativeLayout的顶部,而不是底部。

我还尝试了以下方法:
我所说的后AddView并添加ImageView ,我设置了Y的位置ImageView
这实际上有效。 它将ImageView向下移动,但是我不确定向下移动多少。 RelativeLayout大小不是绝对的。

// this moves the ImageView down 100px.
shadowView.SetY (100f);

如何将其放在RelativeLayout的底部?

请注意:我不能只是做数学运算( RelativeLayout height- ImageView Height),因为在OnCreate完成之前RelativeLayout高度始终为0

我还有其他选择吗?

感谢您的时间。

可能的解决方案:

1。

考虑在RelativeLayout XML中放置一个ImageView。

您可以使用以下方式在“活动/片段”中访问此ImageView:

ImageView mImageView = (ImageView) view.findViewById(R.id.imageView);

您可以设置起始能见度消失mImageView.setVisibility(View.GONE)并显示在稍后的时间ImageView的mImageView.setVisibility(View.VISIBLE) ;

2。

您可以在现有的RelativeLayout上添加一个子布局(LinearLayout),该子布局可以通过XML放置在RelativeLayout的底部。

在“活动/片段”内部,您可以通过其ID定位该子布局(linearLayout),然后以编程方式将ImageView添加到该布局。

<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"
             tools:context="com.modup.fragment.FeedFragment">

    <!-- TODO: Update blank fragment layout -->
       <LinearLayout>
              android:id="@+id/linearLayout"
              android:layout_alignParentBottom="true"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
       </LinearLayout>
</RelativeLayout>

我找到了一个方法!

使用RelativeLayout.LayoutParams完成此工作,而不是使用WindowManagerLayoutParams来设置LayoutParameters。

这是如何做:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.MatchParent, (int)imgViewHeight);
layoutParams.AddRule (LayoutRules.AlignParentBottom);

AlignParentBottom可以完成工作!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM