How to take a component position

How to take a component position?

If we need to place another element in the same place we need to put use LayoutParams.

<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"
<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>

If we have a ImageView in our layout and we need to replace this Image for other element.
We can take the position with margin.

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

Also you can check the example in GitHub

Leave a Reply

Your email address will not be published. Required fields are marked *