如何在android中以编程方式更改relativelayout中的视图的x

时间:2016-01-15 16:52:16

标签: android android-layout android-relativelayout

我在relativeleayout中有一个视图,我想将视图的位置更改为relativeleayout的中间: 我所做的 ?

xml:

<RelativeLayout
    android:id="@+id/partieoption"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="6"
    android:orientation="horizontal" >

   <ImageView 
       android:id="@+id/photo2"
       android:src="@drawable/loglog"
       android:layout_width="50dp"
       android:layout_height="50dp"
   />
</RelativeLayout>

RelativeLayout partieoption = (RelativeLayout) findViewById(R.id.partieoption);
ImageView x = (ImageView) findViewById(R.id.photo2);

4 个答案:

答案 0 :(得分:1)

您需要使用CENTER_IN_PARENT 规则ImageView创建RelativeLayout.LayoutParams,然后将其应用于setLayoutParams(ViewGroup.LayoutParams params)

以下是一个例子:

    ImageView imageView = (ImageView)findViewById(R.id.iv_image);
    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)imageView.getLayoutParams();
    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
    imageView.setLayoutParams(layoutParams);

答案 1 :(得分:0)

 <ImageView 
                        android:id="@+id/photo2"
                        android:src="@drawable/loglog"
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:gravity="center"
                        android:layout_gravity="center"
 />

答案 2 :(得分:0)

要移动视图,请添加此代码

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
RelativeLayout partieoption = (RelativeLayout) findViewById(R.id.partieoption);
      ImageView iv = (ImageView) findViewById(R.id.photo2);
ObjectAnimator transAnimation= ObjectAnimator.ofFloat(iv, x, iv.getX(), width/2);
  transAnimation.setDuration(3000);
  transAnimation.start();

答案 3 :(得分:0)

在xml中使用gravity属性,如下所示:

android:layout_gravity="center"

在你的情况下,我认为会是这样的:

<RelativeLayout
android:id="@+id/partieoption"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="6"
android:orientation="horizontal" >

<ImageView 
   android:id="@+id/photo2"
   android:src="@drawable/loglog"
   android:layout_width="50dp"
   android:layout_height="50dp"
   android:layout_gravity="center"
/>
</RelativeLayout>