ImageView without xml definition

ⅰ亾dé卋堺 提交于 2019-11-27 07:00:09

问题


I want to create a dynamic number of ImageViews in Android. But to display these ImageViews I have to create them in the main.xml (Am I right?) Is there a way to display the ImageViews without creating them in the main.xml?


回答1:


You can create them dynamically like this:

ImageView image=new ImageView(this);

and to set image in this dynamically created view use:

image.setImageResource(R.drawable.yourimage);



回答2:


Put your image my_image.jpg into res/drawable/my_image.jpg and use:

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);
    }
}

Tested on Android 22 with the default template generated by android create project [...].



来源:https://stackoverflow.com/questions/9556020/imageview-without-xml-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!