如何获取组件位置?

时间:2016-02-04 17:59:43

标签: android

在布局中有2个不同位置的imageview所以当我点击黑色时我想要一张新卡同样的位置的imageview,当然还有红色的。例如,黑色的一个 layout_alignParentTop =“true”我希望使用此信息制作新卡片。如何在制作新卡时获取图像视图的位置并使用它们?

enter image description here

1 个答案:

答案 0 :(得分:0)

如果你有边距,你可以这样做:

我的布局:

<RelativeLayout 
android:id="@+id/activity_main_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
<ImageView
    android:id="@+id/activity_main_red_card"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_dark"
    android:layout_marginBottom="@dimen/activity_main_layout_margin_bottom"
    android:layout_marginLeft="@dimen/activity_main_layout_margin_left"
    android:layout_marginRight="@dimen/activity_main_layout_margin_right"
    android:layout_marginTop="@dimen/activity_main_layout_marginB_top"/></RelativeLayout>

我的活动:

public class MainActivity extends AppCompatActivity {

RelativeLayout mRelativeLayout;
ImageView mRedCard, mNewCard;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_main_relative_layout);
    mRedCard = (ImageView) findViewById(R.id.activity_main_red_card);

    mNewCard = new ImageView(this);
    mNewCard.setBackgroundColor(getColor(R.color.colorPrimary));
    takePosition();
}

public void takePosition() {

    RelativeLayout.LayoutParams mLayoutParams = (RelativeLayout.LayoutParams) mRedCard.getLayoutParams();
    mNewCard.setLayoutParams(mLayoutParams);
    mRelativeLayout.addView(mNewCard);
}}

您也可以查看我的example