您的位置:首页 > 移动开发 > Android开发

应用里的用户头像是怎样更改的?

2016-08-10 22:22 761 查看
项目下载地址~~点击打开链接今天有点累,我就直接把代码粘上了,不过我在里面加了注释,方便大家理解。Activity:
public class IntentActivity extends AppCompatActivity implements View.OnClickListener {

private View popView;
private GridView gv1;
private Button popCancel;
private PopupWindow pw;
RoundImageView riv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intent);
Button bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(this);
Button bt2 = (Button) findViewById(R.id.bt2);
bt2.setOnClickListener(this);
Button bt3 = (Button) findViewById(R.id.bt3);
bt3.setOnClickListener(this);
Button bt4 = (Button) findViewById(R.id.bt4);
bt4.setOnClickListener(this);
Button bt5 = (Button) findViewById(R.id.bt5);
bt5.setOnClickListener(this);
Button bt6 = (Button) findViewById(R.id.bt6);
bt6.setOnClickListener(this);
Button bt7 = (Button) findViewById(R.id.bt7);
bt7.setOnClickListener(this);
riv = (RoundImageView) findViewById(R.id.riv);
riv.setOnClickListener(this);
//加载popWindow的布局
popView = getLayoutInflater().inflate(R.layout.popwindow_layout,null);
//        gv1 = (GridView) popView.findViewById(R.id.gv1);
//从popWindow布局中取得控件
popCancel = (Button) popView.findViewById(R.id.popCancle);
popCancel.setOnClickListener(this);
popView.findViewById(R.id.camera).setOnClickListener(this);
popView.findViewById(R.id.photo).setOnClickListener(this);
//        List list = new ArrayList();
//        Map map = new HashMap();
//        map.put("img",R.mipmap.picture04);
//        map.put("name","拍照");
//        list.add(map);
//        map = new HashMap();
//        map.put("img",R.mipmap.picture01);
//        map.put("name","从手机相册选择");
//        list.add(map);
//        map = new HashMap();
//        map.put("img",R.mipmap.picture08);
//        map.put("name","嘿嘿嘿~");
//        list.add(map);
//        SimpleAdapter sa = new SimpleAdapter(this,list,R.layout.gridview_layout,
//                new String[]{"img","name"},new int[]{R.id.iv,R.id.tv});
//        gv1.setAdapter(sa);
//显示Intent,明确的指明它要跳转到哪个Activity
//        Intent intent = new Intent(IntentActivity.this,IntentActivity.class);
//        startActivity(intent);
//隐示Intent,由Android系统帮助匹配
//匹配规则:清单文件中的Intent-filter 标签中的 action
//        Uri uri = Uri.parse("tel:1008611");
//        Intent intent = new Intent(Intent.ACTION_DIAL,uri);
//        startActivity(intent);
}

@Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.bt1:
Uri uri1 = Uri.parse("tel:18865557601");
Intent intent1 = new Intent(Intent.ACTION_CALL, uri1);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(intent1);
break;
case R.id.bt2:
Intent intent2 = new Intent(Intent.ACTION_VIEW);
intent2.putExtra("sms_body","发送短信");
intent2.setType("vnd.android-dir/mms-sms");
startActivity(intent2);
break;
case R.id.bt3:
Uri uri2 = Uri.parse("http://www.baidu.com");
Intent intent3 = new Intent(Intent.ACTION_VIEW,uri2);
startActivity(intent3);
break;
case R.id.bt4:
Intent intent4 = new Intent(Intent.ACTION_VIEW);
File file1 = new File("/storage/sdcard1/2015.8.22酷派/酷派8297数据/1989/01 Welcome To New York.m4a");
intent4.setDataAndType(Uri.fromFile(file1),"audio/*");
startActivity(intent4);
break;
case R.id.bt5:
Intent intent5 = new Intent(Intent.ACTION_VIEW);
File file2 = new File("/storage/sdcard1/video/虫子.jpeg");
intent5.setDataAndType(Uri.fromFile(file2),"image/*");
startActivity(intent5);
break;
case R.id.bt6:
Intent intent6 = new Intent(Intent.ACTION_VIEW);
intent6.setDataAndType(Uri.parse("file:///storage/sdcard1/video/Beytagh最佳.apk"),
"application/vnd.android.package-archive");
startActivity(intent6);
break;
case R.id.bt7:
notification();
break;
case R.id.riv:
pw = getPopWindow(popView);
break;
case R.id.popCancle:
pw.dismiss();
break;
case R.id.camera:
tackPhoto();
break;
case R.id.photo:
phonePhoto();
break;

}
}

/*
调用图库
*/
public void phonePhoto(){
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,2);
}

/*
调用相机
*/
private String capturePath ="";
public void tackPhoto(){
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File parent = FileUitlity.getInstance(getApplicationContext())
.makeDir("head_img");
//给拍完的照片起名字
capturePath = parent.getPath()
+File.separatorChar
+System.currentTimeMillis()
+".jpg";
camera.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(capturePath)));
camera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
//该方法的值会返回到onActivityResult里
startActivityForResult(camera,1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != Activity.RESULT_OK){
Toast.makeText(this,"系统异常",Toast.LENGTH_SHORT).show();
return;
}
//相机返回结果,再去调用系统裁剪
if(requestCode==1){
startPicZoom(Uri.fromFile(new File(capturePath)));
}//相册返回结果,再去调用系统裁剪
else if(requestCode==2){
//Cursor相当于一个指针,是一个结果集,一个游标
Cursor cursor = getContentResolver().query(data.getData(),
new String[]{MediaStore.Images.Media.DATA},null,null,null);
cursor.moveToFirst();
String capturePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
startPicZoom(Uri.fromFile(new File(capturePath)));
}else if(requestCode==3){
Bundle bundle = data.getExtras();
if(bundle!=null){
Bitmap bitmap = bundle.getParcelable("data");
riv.setImageBitmap(bitmap);
}
pw.dismiss();

}
}

//消息栏通知
public void notification(){
//先定义一个Intent
Intent intent = new Intent(this,SecondActivity.class);
//使用PendingIntent 封装 Intent
/*PendingIntent第四个参数(常量)的种类及说明:
FLAG_CANCEL_CURRENT:如果要创建的PendingIntent已经存在了,
那么在创建新的PendingIntent之前,原先已经存在的PendingIntent中的intent将不能使用

FLAG_NO_CREATE:如果要创建的PendingIntent尚未存在,则不创建新的PendingIntent,直接返回null

FLAG_ONE_SHOT:相同的PendingIntent只能使用一次,且遇到相同的PendingIntent时不会
去更新PendingIntent中封装的Intent的extra部分的内容

FLAG_UPDATE_CURRENT:如果要创建的PendingIntent已经存在了,那么在保留原
先PendingIntent的同时,将原先PendingIntent封装的Intent中的extra部分替换为现
在新创建的PendingIntent的intent中extra的内容
*/
PendingIntent pi = PendingIntent.getActivities(this,0,new Intent[]{intent},
PendingIntent.FLAG_UPDATE_CURRENT);
//获取通知服务
NotificationManager nm = (NotificationManager)
getSystemService(Activity.NOTIFICATION_SERVICE);
//设置各个属性
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("A")
.setContentInfo("我是通知栏信息")
.setContentTitle("奥运会")
.setContentText("PendingIntent使用演示")
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pi)
.build();
//通过通知服务显示通知栏,这个0是Id,如果再设置一个通知,而ID不变的话,那么会覆盖掉该通知
nm.notify(0,notification);
}

//设置PopWindow背景透明度的方法
public void backgroundAlpha(float bgAlpha){
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha= bgAlpha;
getWindow().setAttributes(lp);
}

//构建一个popwindow
//方法PopWindow
public PopupWindow getPopWindow(View view){
PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT,false);
popupWindow.setAnimationStyle(R.style.pop1);
//设置背景透明度
backgroundAlpha(0.6f);
//-------------
//获取光标
popupWindow.setOutsideTouchable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable());
//显示的位置,第一个参数为参照物,随便找一个就行
popupWindow.showAtLocation(riv, Gravity.BOTTOM,0,0);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
backgroundAlpha(1f);
}
});
return popupWindow;
}

/*
调用系统的裁剪功能
*/
public void startPicZoom(Uri uri){
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri,"image/*");
//允许裁剪
intent.putExtra("crop","true");
//设置裁剪比例
intent.putExtra("aspectX",1);
intent.putExtra("aspectY",1);
//设置图片的高度和宽度
intent.putExtra("outputX",150);
intent.putExtra("outputY",150);
//是否返回数据
intent.putExtra("return-data",true);
startActivityForResult(intent,3);
}
}
Layout:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingRight="10dp">
<jerehdu.com.jereduch09.RoundImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/riv"
android:src="@mipmap/picture07"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="center"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拨打电话"
android:textSize="30sp"
android:id="@+id/bt1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送短信"
android:textSize="30sp"
android:id="@+id/bt2"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt3"
android:textSize="30sp"
android:text="打开网页"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt4"
android:textSize="30sp"
android:text="播放音乐"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt5"
android:textSize="30sp"
android:text="浏览图片"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt6"
android:textSize="30sp"
android:text="安装APK"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bt7"
android:textSize="30sp"
android:text="通知栏消息"/>

</LinearLayout>
</ScrollView>
RoundImageView让图片变圆的工具类(直接复制即可):
<pre name="code" class="java">public class RoundImageView extends ImageView {
public RoundImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas) {

Drawable drawable = getDrawable();

if (drawable == null) {
return;
}

if (getWidth() == 0 || getHeight() == 0) {
return;
}

Bitmap b = null;
if(drawable instanceof BitmapDrawable){
b = ((BitmapDrawable) drawable).getBitmap();
}else if(drawable instanceof Drawable){
b = Bitmap.createBitmap(
getWidth(),
getHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas1 = new Canvas(b);
// canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, getWidth(),
getHeight());
drawable.draw(canvas1);
}

if (null == b) {
return;
}

Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth(), h = getHeight();

Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);

}

public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius)
sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
else
sbmp = bmp;
Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xffa19774;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(sbmp.getWidth() / 2 + 0.7f,
sbmp.getHeight() / 2 + 0.7f, sbmp.getWidth() / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
FileUitlity给相机拍照的照片设置存放文件夹的工具类(可直接复制)
public class FileUitlity {

public final static String USER_HAED="head";

private static String ROOT_CACHE;
public static String ROOT_DIR="yt_xyt";
private static FileUitlity instance = null;
private FileUitlity() {
}
public static FileUitlity getInstance(Context context) {
if (instance == null) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
ROOT_CACHE = (Environment.getExternalStorageDirectory() + "/"
+ ROOT_DIR + "/");
} else {
ROOT_CACHE = (context.getFilesDir().getAbsolutePath() + "/"+ROOT_DIR+"/");
}
File dir = new File(ROOT_CACHE);
if (!dir.exists()) {
dir.mkdirs();
}
instance = new FileUitlity();
}
return instance;
}
public File makeDir(String dir) {
File fileDir = new File(ROOT_CACHE + dir);
if (fileDir.exists()) {
return fileDir;
} else {
fileDir.mkdirs();
return fileDir;
}
}

}
因为要用到PopWindow,所以建一个PopWindow的layout:
    <GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/gv1"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:cacheColorHint="#00000000"
android:listSelector="#00000000"
android:scrollbars="none">
</GridView>
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="相机"
android:id="@+id/camera"
android:gravity="center"
android:layout_gravity="center"/>
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="从相册中选择"
android:id="@+id/photo"
android:gravity="center"
android:layout_gravity="center"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#acacac"
android:layout_marginTop="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/popCancle"
android:text="取消分享"
android:layout_marginTop="5dp"
android:layout_gravity="center"/>
千万记得在清单文件AndroidManifest中设置权限哦~
    <!-- 打电话权限 -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<!-- 上网权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 读写数据权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我这里面用到了两个动画效果设置了下PopWindow的动画:
pop_enter1
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<translate
android:duration="500"
android:fromYDelta="100%p"
android:toYDelta="0"/>
<alpha android:fromAlpha="0"
android:toAlpha="1"
android:duration="500"/>
</set>
pop_exit1
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<translate
android:duration="500"
android:fromYDelta="0"
android:toYDelta="100%p"/>
<alpha android:fromAlpha="1"
android:toAlpha="0"
android:duration="500"/>
</set>
记得在Styles文件夹中定义个样式:
    <style name="pop1">
<item name="android:windowEnterAnimation">@anim/pop_enter1</item>
<item name="android:windowExitAnimation">@anim/pop_exit1</item>
</style>
OK,效果图如下:

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐