【问题标题】:How to create multiple copies of ImageView object programmatically?如何以编程方式创建 ImageView 对象的多个副本?
【发布时间】:2013-03-28 20:18:28
【问题描述】:

我有一个 ImageView 对象,R.id.tile,在我的 XML 布局中定义,我想做的是创建它的克隆并将它们中的每一个放置在不同的坐标处。

这是我目前所拥有的:

    protected void onCreate(Bundle savedInstance)
    {   super.onCreate(savedInstance);
        setContentView(R.layout.board_layout);
        layout = (AbsoluteLayout)findViewById(R.id.board);
        img = (ImageView)findViewById(R.id.tile);
        View[] tiles = new ImageView[9];
        for (int i = 0; i<tiles.length; i++) {
            tiles[i] = (ImageView)findViewById(R.id.tile);
        }

        for(int i=0; i<3; i++){
            for(int j=0; j<3; j++){
                tiles[i+j].setX((float) 32*2*i);
                tiles[i+j].setY((float) 34.39*2*j);
            }
        }
     ...

但是当我调试它时,它一直停在 tiles[i] = (ImageView)findViewById(R.id.tile);
出现错误“找不到源。”

有什么想法吗?

【问题讨论】:

  • 您尝试使用原始 ImageView 的克隆而不是制作新的并将其 Image 设置为相同是否有特定原因?我认为后一种方法会容易得多。然后,您可以致电 layout.addView(tiles[i]); 将新的添加到您的布局中。
  • @FoamyGuy 可能是他不想以编程方式为所有这些设置原始图像视图获取的所有属性或样式,例如高度、宽度等。
  • @Pragnani 可能,如果是这种情况,那么他可以在其 on layout.xml 文件中声明 ImageView,然后使用 LayoutInflater 创建新的,这将使它们全部预先设置到所需的配置。
  • @FoamyGuy 是的...同意..

标签: android imageview clone inflate


【解决方案1】:

activity_main.xml

<LinearLayout
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
</LinearLayout>

MainActivity.java

ImageView iv;
LinearLayout linear;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    linear = new LinearLayout(this);
    linear = (LinearLayout)findViewById(R.id.linear);

    for(int i=1;i<10;i++)
    {
        iv = new ImageView(this);
        iv.setImageResource(R.drawable.plus);
        iv.setPadding(0,0,0,20);
        linear.addView(iv);
    }
}

应用视图看起来像这样 app view

【讨论】:

    【解决方案2】:
    ImageView imageview=new ImageView(context);
    

    imageview=yourimageview // 原件的副本

    对于你的问题,试试这个

    View[] tiles = new ImageView[9];
    ImageView testview= (ImageView)findViewById(R.id.testview);
    
    for (int i = 0; i<tiles.length; i++) {
                tiles[i] = new Imageview(context);
            }
    

    【讨论】:

    • 我使用了这些更改,并且没有更多错误(耶!),但只有 tiles 的第 9 个实例(最后一个元素)出现在布局上。我猜这是因为tiles 数组的每个元素都指向同一个对象?
    • @AdamChoate 是的...采取一个单独的布局,其中包含单个图像视图..然后膨胀 ImageView 以获取它的副本..并使用该图像..作为 FoamGuy 建议的
    • 我是否必须为 imageview 的每个实例创建一个新布局?你能告诉我怎么做吗?
    • 感谢您的快速回复 :) 无论如何,我已经提出了一个关于如何为多个视图对象充气的新问题:How to inflate new copies of an ImageView object on a layout?
    • 代码没有意义。你分配了两次tile[i]。指令“tiles[i] = new Imageview(context);”应该没有影响
    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多