Android Studio - Java - 将ImageView附加到XML文件中定义的布局

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

我的代码如下:

ImageView iv = new ImageView(R.layout.activity_main_menu);

我得到的错误是:

ImageView (android.content.Context) in ImageView cannot be applied to (int)

我猜我的布局想要返回一个整数值,我只想将我的ImageView设置为我的布局,谢谢你的帮助!

编辑:

enter image description here

编辑2:

我将我的布局设置为显示,我可以在运行应用程序时看到它,我将背景设置为绿色,所以我确信:

setContentView(R.layout.activity_main_menu);

这是.xml文件:

FrameLayout 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"
    android:background="#162216"
    tools:context=".main.MainMenuActivity">
</FrameLayout>

我定义了我的布局,定义了我的ImageView,问题是如何将它们配对,以便ImageView成为布局的一部分,因此它可以显示为图片?

虽然我的布局是在.xml文件中定义的,但我的ImageView直接写入我的.java类

android layout imageview parent
2个回答
2
投票

即使这个解决方案是错误的,也不要那样做。

XML:

<FrameLayout 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:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#162216"
    tools:context=".main.MainMenuActivity">
</FrameLayout>

码:

FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(R.drawable.imageResource);
frameLayout.addView(imageView);

如果您想要以后拥有大量图像,则需要将它们放在回收站视图中,最有可能的是,您可能不需要对它们进行回收,因此您将使用解决方案将它们添加到LinearLayout中。

注意:FrameLayout只能有一个孩子


0
投票

在onCreate方法中设置R.layout.activity_main_menu)像这样:

的setContentView(R.layout.activity_main_menu);

然后从xml设置imageView ID

ImageView iv = new ImageView(this);

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