【问题标题】:ImageView without xml definition没有xml定义的ImageView
【发布时间】:2012-03-04 15:14:10
【问题描述】:

我想在 Android 中创建动态数量的 ImageView。 但是要显示这些 ImageView,我必须在 main.xml 中创建它们(对吗?) 有没有办法显示 ImageViews 而无需在 main.xml 中创建它们?

【问题讨论】:

  • 不,您可以像 ImageView image=new ImageView(this); 一样动态创建它们;

标签: android imageview


【解决方案1】:

您可以像这样动态创建它们:

ImageView image=new ImageView(this);

并在这个动态创建的视图中设置图像:

image.setImageResource(R.drawable.yourimage);

【讨论】:

  • 是的,但是如果我写类似这样的 ImageView iv = (ImageView) findViewById(R.id.imageview1);,我只能显示这个 ImageView
  • 您不必编写任何类似的代码。动态创建线性布局并在您想要的特定线性布局中添加尽可能多的图像视图
【解决方案2】:

将您的图像my_image.jpg 放入res/drawable/my_image.jpg 并使用:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.my_image);
        setContentView(imageView);
    }
}

使用android create project [...]生成的默认模板在Android 22上测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多