【发布时间】:2015-06-11 19:45:14
【问题描述】:
我想在我的应用程序中的按钮上设置图像,从 sdcard 上的文件动态设置。我已经尝试过这段代码,但它不起作用。我试图将图像转换为位图对象并将该对象设置为 ImageButton,但它没有显示任何内容。我该如何解决这个问题?
我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File imageFile = new File("/sdcard0/DCIM/camera/jbn.jpg");
Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageButton button1 = (ImageButton)findViewById(R.id.imgBtn);
button1.setImageBitmap(bmp);
}
XML
<ImageButton
android:layout_width="200dip"
android:layout_height="200dip"
android:id="@+id/imgBtn"
/>
算法
void loadPic()
{
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathName = baseDir + "/DCIM/camera/";
File parentDir=new File(pathName);
File[] files = parentDir.listFiles();
Date lastDate;
String lastFileName;
boolean isFirstFile = true; //just temp variable for being sure that we are on the first file
for (File file : files) {
if(isFirstFile){
lastDate = new Date(file.lastModified());
isFirstFile = false;
}
if(file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")){
Date lastModDate = new Date(file.lastModified());
if (lastModDate.after(lastDate)) {
lastDate = lastModDate;
lastFileName = file.getName();
}
}
}
【问题讨论】:
-
看看这个库对我帮助很大...square.github.io/picasso
-
你能发布你的布局文件吗?你的jpg大小是多少?您是否添加了从文件系统读取文件的权限?
-
@user3431672:我已添加读取权限,请查看我的编辑
标签: android android-bitmap android-imagebutton