【问题标题】:How to change layout:alignEnd, alignComponent attributes programatically如何更改布局:对齐结束,以编程方式对齐组件属性
【发布时间】:2015-12-20 07:23:15
【问题描述】:

我有 2 张图片,一张站在另一张后面,是黄色背景,突出 20dp,它是一个框架。前图为主图。

点击时,我希望主图像出现在“黄框”的中心。

<ImageView

    android:id="@+id/yellow_bkg"
    android:background="#ffe467"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
     />

<ImageView    
    android:id="@+id/card"
    android:background="@drawable/card"
    android:layout_alignRight="@+id/border"   //how to change this in code?
    android:layout_alignEnd="@+id/border"//how to change this in code?
    android:layout_margin="20dp" />

但效果应该发生在代码中,即当我点击或触摸卡片图像视图时动态发生。

【问题讨论】:

标签: android xml android-layout alignment android-imageview


【解决方案1】:

您可以使用 LayoutParams 来做到这一点!

ImageView card = (ImageView) findViewById(R.id.card);

因为你有

android:layout_alignRight="@+id/border"
android:layout_alignEnd="@+id/border"

我假设你在一个 RelativeLayout

RelativeLayout.LayoutParams layoutParams;
layoutParams = new RelativeLayout.LayoutParams(width, height);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

在你的图像视图中点击Listner

card.setLayoutParams(layoutParams);

【讨论】:

  • @Sharma,好的,但是当我创建新的相对布局参数时,我的 imageView 已经在另一个 relativeLayout 中,如果我执行 card.setLayoutParams,它如何影响我的 imageView 所在的实际相对布局?
  • 它不会影响您的实际相对布局。实际上,可以在视图上设置的属性类型与其父视图有关。您可能希望使用与父视图相同类型的 LayoutParams。这样您就可以使用您需要的那些属性..就像在您的情况下您想使用 CENTER_IN_PARENT
猜你喜欢
  • 2016-07-17
  • 1970-01-01
  • 2013-03-07
  • 2017-06-19
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多