0
我到处搜索,但似乎没有找到解决方案。无法将图像加载到imageview
在我的应用程序,我有以下布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_marginTop="68dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="57dp"
android:layout_marginTop="176dp"
android:text="Load from Gallery" />
</RelativeLayout>
在按钮的点击我显示一个文件使用achooser库项目从GitHub选择。 MainActivity的代码是:
public class MainActivity extends SherlockActivity {
private static final int REQUEST_CODE = 6384;
Uri uri = null;
String path = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button chooseFile = (Button) findViewById(R.id.button1);
chooseFile.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showChooser();
ImageView MyImageView = (ImageView) findViewById(R.id.imageView1);
Drawable d = Drawable.createFromPath(path);
MyImageView.setImageDrawable(d);
MyImageView.refreshDrawableState();
}
});
}
private void showChooser() {
// Use the GET_CONTENT intent from the utility class
Intent target = FileUtils.createGetContentIntent();
// Create the chooser Intent
Intent intent = Intent.createChooser(target, "Choose Image");
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// The reason for the existence of aFileChooser
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE:
// If the file selection was successful
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
uri = data.getData();
try {
// Create a file instance from the URI
final File file = FileUtils.getFile(uri);
path = file.getAbsolutePath();
} catch (Exception e) {
Log.e("FileSelectorTestActivity", "File select error",
e);
}
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
选择图像时,什么都不会发生。我的意思是既没有例外,也没有加载图像。在logcat中,我看到:
您是否尝试调试应用程序以查看它出错的位置? – Egor
我添加了一个sysout来查看我在Drawable中设置的路径d = Drawable.createFromPath(path);是正确的,我看到正确的道路。点击选择器中的图像后,我将返回该位置。但MyImageView.setImageDrawable(d);似乎无法设置ImageView。 – Sandeep