以编程方式更改视图位置

时间:2019-04-05 10:25:31

标签: android android-view

我已通过以下方式将xml布局添加到主布局中:

View customView = LayoutInflater.from(requireContext()).inflate(R.layout.anim_map_toolbar, null);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
    params.gravity = Gravity.RIGHT;
    params.rightMargin = 20;
    params.topMargin = 20;
    customView.setLayoutParams(new FrameLayout.LayoutParams(params));
View animationView = customView.findViewById(R.id.anim_toolbar);
mainConstraintLayout.addView(customView);

但是此布局出现在主布局的顶部和左侧。我想用主布局的顶部和右侧的边距将位置更改为右上方!!!

我用过

params.gravity = Gravity.RIGHT;

params.rightMargin = 20;

params.topMargin = 20;

但是它不起作用,并且视图仍然位于右侧和顶部位置!!!

这是主要布局xml:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.MapFragment"
    android:id="@+id/main_constraintLayout">

</android.support.constraint.ConstraintLayout>

这是anim_map_toolbar.xml布局:

<android.support.v7.widget.LinearLayoutCompat
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="56dp"
    android:layout_height="56dp"
    android:orientation="horizontal"
    android:background="@drawable/animate_toolbar_style"
    android:gravity="center">

    <android.support.v7.widget.AppCompatImageView
        android:id="@+id/imv_setting"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_gravity="center"
        android:adjustViewBounds="false"
        android:cropToPadding="false"
        app:srcCompat="@drawable/ic_settings" />
</android.support.v7.widget.LinearLayoutCompat>

1 个答案:

答案 0 :(得分:0)

根据@Mikem建议,我已更改为:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
        params.rightMargin = 20;
        params.topMargin = 20;
        customView.setLayoutParams(params); 

并且我已经将ConstraintLayout从主xml布局转换为RelativeLayout

现在,我的问题消失了..谢谢@Mikem