80,351
社区成员
发帖
与我相关
我的任务
分享
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/pic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/ic_background_20_48dp" />
</LinearLayout>
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
/**
* Created by 97890 on 2017/8/28.
*/
public class PicFragment extends Fragment {
private static final String TAG = "PicFragment";
private static final String sourcePathKey = "Path";
private String sourcePath;
//sourcePath是外部存储中的一张图片的路径,在onCreateView()中初始化
private ImageView pic;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.layout_fragment,container,false);
pic = v.findViewById(R.id.pic);
sourcePath = getArguments().getString(sourcePathKey);
showPic();
//如果注释掉这句,Fragment中的ImageView将显示默认的图片(drawable/ic_background_20_48dp.png)
//如果取消注释这句,Fragment中的ImageView将一片空白,不显示我指定的,存放在外部存储的图片
return v;
}
//空的构造方法
public PicFragment(){
super();
}
//创建一个PicFragment的对象,传参并返回该对象
public static PicFragment createdFragment(String sourcePath){
PicFragment fragment = new PicFragment();
Bundle args = new Bundle();
args.putString(sourcePathKey, sourcePath);
fragment.setArguments(args);
return fragment;
}
//将路径为sourcePath的图片显示到ImageView中
public void showPic(){
Bitmap bm = getLoacalBitmap();
if(bm != null)
pic.setImageBitmap(bm);
}
//解码路径为sourcePath的图片,并返回一个Bitmap的对象
public Bitmap getLoacalBitmap() {
File file = new File(sourcePath);
if(file.exists()){
Bitmap bitmap = BitmapFactory.decodeFile(sourcePath);
return bitmap;
}
else
return null;
}
}