public class LeftFragment extends Fragment implements OnClickListener {
private View view;
private ImageView img_icon;
private Button btn_shang;
private PopupWindow window;
private Button btn_xiangce;
private Button btn_paizhao;
private String path = Environment.getExternalStorageDirectory()+"/head.jpg";
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_left, container, false);
img_icon = (ImageView) view.findViewById(R.id.img_icon);
btn_shang = (Button) view.findViewById(R.id.btn_shang);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//1.创建popupwindow
View contentView = View.inflate(getActivity(), R.layout.pop_layout, null);
window = new PopupWindow(contentView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
window.setFocusable(true);
window.setTouchable(true);
window.setOutsideTouchable(true);
window.setBackgroundDrawable(new BitmapDrawable());
btn_xiangce = (Button) contentView.findViewById(R.id.btn_xiangce);
btn_paizhao = (Button) contentView.findViewById(R.id.btn_paizhao);
//2.点击按钮,,显示popupwindow
btn_shang.setOnClickListener(this);
btn_xiangce.setOnClickListener(this);
btn_paizhao.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_shang:
//显示popupwindow
window.showAtLocation(view, Gravity.BOTTOM, 0, 0);
break;
case R.id.btn_xiangce:
//打开相册
Intent xcIntent = new Intent(Intent.ACTION_PICK);
xcIntent.setType("image/*");
startActivityForResult(xcIntent, 99);
//关闭窗口
window.dismiss();
break;
case R.id.btn_paizhao:
//打开相机
Intent xjIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
xjIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(path)));
startActivityForResult(xjIntent, 89);
//关闭窗口
window.dismiss();
break;
default:
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 99 && resultCode == getActivity().RESULT_OK) {
crop(data.getData());
}
if (requestCode == 89 && resultCode == getActivity().RESULT_OK) {
crop(Uri.fromFile(new File(path)));
}
if (requestCode == 100 && resultCode == getActivity().RESULT_OK) {
Bitmap bitmap = data.getParcelableExtra("data");
img_icon.setImageBitmap(bitmap);
}
}
/*
* 裁剪的方法
*/
private void crop(Uri uri) {
Intent cjIntent = new Intent("com.android.camera.action.CROP");
cjIntent.setDataAndType(uri, "image/*");
cjIntent.putExtra("crop", "true");
cjIntent.putExtra("aspectX", 1);
cjIntent.putExtra("aspectY", 1);
cjIntent.putExtra("outputX", 251);
cjIntent.putExtra("outputY", 251);
cjIntent.putExtra("return-data", true);
startActivityForResult(cjIntent, 100);
}
}