【问题标题】:Add imageview programmatically constraints problem以编程方式添加 imageview 约束问题
【发布时间】:2020-04-20 13:47:20
【问题描述】:

我正在使用Android Studio 构建一个应用程序(用于Android),但在以编程方式将ImageView 添加到我的FrameLayout 的位置方面,我遇到了一些麻烦。

第一件事:我在FrameLayout 上有一个初始的ImageView,称为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,但程序将新图像放置在FrameLayout 的位置(0, 0)。我很确定这与我添加的新 ImageView 的约束设置有关,但我无法解决这个问题。有谁知道我怎样才能将新的ImageView 放在(10, 100) 的位置?谢谢。

【问题讨论】:

    标签: java android xml imageview


    【解决方案1】:

    我认为您可以通过向 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”

    【讨论】:

    • 谢谢!我改用layoutParams.setTop,但这是同一个概念!如此简单.. ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2015-02-21
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多