簡體   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