簡體   English   中英

如何在Android中以編程方式更改相對布局中視圖的x

[英]how to change the x of view in relativelayout Programmatically in android

我在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);

您需要使用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);
 <ImageView 
                        android:id="@+id/photo2"
                        android:src="@drawable/loglog"
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:gravity="center"
                        android:layout_gravity="center"
 />

要移動視圖,請添加以下代碼

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();

使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM