以编程方式添加imageview约束问题

问题描述 投票:0回答:1

我正在使用Android构建一个应用程序(针对Android Studio,并且在以编程方式添加ImageView到我的FrameLayout的位置时遇到了一些麻烦。

首先,我在ImageView上有一个初始的FrameLayout,名为AVATAR01,正如您在xml文件上看到的那样:

<FrameLayout
    android:id="@+id/LayJog"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="0dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
    <ImageView
        android:id="@+id/AVATAR01"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@drawable/avatar01" />
</FrameLayout>

然后,我使用下一个JAVA代码添加另一个ImageView,类似于我之前已经声明的代码:

//Objects:
    ImageView IMG01 = (ImageView) findViewById(R.id.AVATAR01);
    FrameLayout LAYJOG = (FrameLayout) findViewById(R.id.LayJog);
    ViewGroup.LayoutParams LAYPAR = new ViewGroup.LayoutParams(IMG01.getLayoutParams());
    ViewGroup.MarginLayoutParams MARPAR = new ViewGroup.MarginLayoutParams(IMG01.getLayoutParams());
//New ImageView:
    ImageView IMG02 = new ImageView(getApplicationContext());
    IMG02.setLayoutParams(new ViewGroup.LayoutParams(LAYPAR));
    IMG02.setLayoutParams(new ViewGroup.MarginLayoutParams(MARPAR));
    IMG02.setTop(100);
    IMG02.setImageResource(R.drawable.avatar02);
    LAYJOG.addView(IMG02);

上面的代码没有任何runtime errors,但是程序将新图像放置在(0, 0)的位置FrameLayout。我很确定这与我添加的新ImageView的约束设置有关,但是我无法解决此问题。有谁知道如何将新的ImageView放在位置(10, 100)?谢谢。

java android xml imageview
1个回答
0
投票

我认为您可以通过在ImageView中增加边距来解决此问题。例如:

LinearLayout layout = findViewById(R.id.layout);

    ImageView IMG02 = new ImageView(this);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT , LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(LEFT , TOP , RIGHT , BOTTOM);
    IMG02.setLayoutParams(layoutParams;

    layout.addView(IMG02);

您必须插入值,而不是“ LEFT,TOP,RIGHT,BOTTOM”

© www.soinside.com 2019 - 2024. All rights reserved.