美文网首页
常用方法3

常用方法3

作者: 小酷哥 | 来源:发表于2017-06-12 10:15 被阅读0次

    101)图片去色,返回灰度图片
    102)把图片变成圆角
    103)在代码中从资源文件中获取一张Bitmap图片
    104)自定义组件属性时,命名空间可以这样写
    105)ic_lunach尺寸设置
    106) android软键盘以及输入法影响界面布局的问题
    107) 给activity设置字体默认颜色和字体大小
    108) 剪切图片
    109) 获取当前线程名称
    110) 代码中设置view的宽高
    111) SharedPreferences的改变监听
    112) 关于屏幕距离的一些知识
    113) listView隔行设置颜色
    114) 根据横竖屏不同状态 设置不同的显示界面
    115) 保持界面常亮
    116) 延迟主线程的某种操作
    117) 获取网络页面资源流
    118) Listview和RadioButton一起使用时
    119) edittext可以录入浮点型
    120) 有下标的选择
    121) 利用ContentProvider扫描手机中所有图片
    122) 点击Listview的item项,没有反应问题
    123) 如果当前activity的启动模式是singleTask...则它上个界面给它传来的bundle都不能接收到
    124) 单例模式模板
    125) 在组件四周添加图片的方法
    126) 选择器属性详解
    127) seekBar组件的样式
    128) 给PopupWindow设置动画效果
    129) 16进制颜色设置
    130) 在一个程序中启动另一个程序
    131) 让自己的应用也成为系统照相机
    132) 存放数据到sd卡,不同方法的区别
    133) activity系统自动动画
    134) 动态创建组件到布局
    135)判断耳机孔是否被插入
    136) Radiogroup中的radioButton都不可编辑方法
    137) 防止按钮连续点击
    138) 系统默认参数
    139) 去除默认GridView的边距
    140) dp和px直接转换方法
    141) style添加自定义组件属性值
    142) Fragment使用方法
    143) list 的 遍历方式
    144) 使用系统相机和系统相册获取图片
    145) 将图片保存到sd卡文件夹下后,图库无法显示的问题
    146) listview中的一些常见大坑
    147) Handler的静态使用

    1. 网络连接超时设置
      149) List 去除元素的方法
      150) 流转转化成字符串
    101)图片去色,返回灰度图片
       /**
             * 图片去色,返回灰度图片
             *
             * @param bmpOriginal 传入的图片
             * @return 去色后的图片
             */
            public static Bitmap toGrayscale(Bitmap bmpOriginal) {
                int width, height;
                height = bmpOriginal.getHeight();
                width = bmpOriginal.getWidth();
                Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                Canvas c = new Canvas(bmpGrayscale);
                Paint paint = new Paint();
                ColorMatrix cm = new ColorMatrix();
                cm.setSaturation(0);
                ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
                paint.setColorFilter(f);
                c.drawBitmap(bmpOriginal, 0, 0, paint);
                return bmpGrayscale;
            }
    
            
    
    102)把图片变成圆角
       public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
            Bitmap output = Bitmap
                    .createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            final float roundPx = pixels;
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
        }
    
    103)在代码中从资源文件中获取一张Bitmap图片
           
            Bitmap dragBitmap = BitmapFactory.decodeResource(mContext.getResources(),
                        R.drawable.getup_slider_ico_normal);
    
    
    104)自定义组件属性时,命名空间可以这样写:
          xmlns:ProgressWheel="http://schemas.android.com/apk/res-auto"
    
    105)ic_lunach尺寸设置
        m: 48*48   h:72*72    xh: 96*96  xxh: 144*144 
    
    106) android软键盘以及输入法影响界面布局的问题
    
       在androidMainfest.xml文件中在此Activity中写入 android:windowSoftInputMode="adjustPan"
    
    
    107) 给activity设置字体默认颜色和字体大小:
        styles.xml
          <style name="AppTheme" parent="@android:style/Theme.Light.NoTitleBar">
            <item name="android:textSize">42dp</item>
            <item name="android:textColor">#FF0000</item>
          </style>
       AndroidManifest.xml文件中引用主题
          <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
    
    108) 剪切图片
     
        res/drawable/drawable_clip.xml
          <clip xmlns:android="http://schemas.android.com/apk/res/android" 
            android:drawable="@drawable/phone2"
            android:clipOrientation="vertical"
            android:gravity="top">
        </clip>
      
       <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/drawable_clip" />
    
            mageView=(ImageView)this.findViewById(R.id.imageView1);
            mDownloadProgressDrawable = (ClipDrawable)imageView.getDrawable();
            mDownloadProgressDrawable.setLevel(100*50);  //0-10000
    
    
    109) 获取当前线程名称:
          Thread.currentThread().getName(); 如果是main 的话,就是主进程
    
    110)代码中设置view的宽高
          LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) mInfo.getLayoutParams(); 
          linearParams.height = 800;
          mInfo.setLayoutParams(linearParams);
         
    111) SharedPreferences的改变监听
    
           sp=getSharedPreferences("key",Context.MODE_PRIVATE);
           sp.registerOnSharedPreferenceChangeListener(this);  
    
    112) 关于屏幕距离的一些知识
            标题栏:48dp
            左右边距:16dp
            两个组件的边距:8dp
            字体大小:14(small),18(middle),22(L)
            laular图标:m(160dpi):48*48   h(240dpi):72*72   x(320dpi): 96*96  xx(480dpi): 144*144 xxx:192*192
    
    
    113) listView隔行设置颜色
       private int[] colors = new int[] { 0x30FF0000, 0x300000FF };  
        @Override  
        public View getView(int position, View convertView, ViewGroup parent) {  
          View view = super.getView(position, convertView, parent);  
    
          int colorPos = position % colors.length;  
          view.setBackgroundColor(colors[colorPos]);  
    
          return view;  
        }  
    
    
    114) 根据横竖屏不同状态 设置不同的显示界面
    
         if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                // 横屏
                setContentView(R.layout.main_l);
          } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                // 竖屏
                setContentView(R.layout.main);
          }
       
    115) 保持界面常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    
    116) 延迟主线程的某种操作
         new Handler().postDelayed(new Runnable() {             
                @Override
                public void run() {
                    MCIntent.sendIntent(PatientAddActivity1.this, PatientDataActivity.class,"patientInfo",mPatientInfo);
                    MCProgress.dismiss();
                    finish();
                }
          }, 1000);
    
        
    117) 获取网络页面资源流
       try {
                URL url=new URL("http://123.57.14.154:28080/MPD/consultation/consultationListPre.do");
                
                System.out.println("协议:"+url.getProtocol());
                System.out.println("域名:"+url.getHost());
                System.out.println("端口:"+url.getPort());
                System.out.println("资源:"+url.getFile());
                System.out.println("相对路径:"+url.getFile());
                System.out.println("锚点:"+url.getRef());
                System.out.println("参数:"+url.getQuery());
                
                //1.获取资源
                InputStream is = url.openStream();
                byte[] flush=new byte[1024];
                int len=0;
                while((len=is.read(flush)) != -1){
                    System.out.println(new String(flush,0,len));
                }
                is.close();
    
           
                //2.另一种获取资源 可以改变编码
                BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));          
                String msg=null;
                while((msg=br.readLine())!=null){
                    System.out.println(msg);
                }
                br.close();
    
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
    118) Listview和RadioButton一起使用时
    
      RadioButton设置 android:focusable="false"
    
    119) edittext可以录入浮点型
    view_conent2_ed.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
    
    editText.setInputType(InputType.TYPE_CLASS_NUMBER);
    editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)}); 
    
    view_conent_ed.setInputType(InputType.TYPE_CLASS_NUMBER| InputType.TYPE_NUMBER_FLAG_DECIMAL);
                view_conent_ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(conentLength)});
    
    
    120) 有下标的选择
    
    private void initImageLine() {
            image = (ImageView) findViewById(R.id.cursor);
            bmpW = BitmapFactory.decodeResource(getResources(),
                    R.drawable.line_blue).getWidth();
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenW = dm.widthPixels;
            offset = (screenW / 4- bmpW) / 2; //4是将屏幕分成4分
    
            // imgageview设置平移,使下划线平移到初始位置(平移一个offset)
            Matrix matrix = new Matrix();
            matrix.postTranslate(offset, 0);
            image.setImageMatrix(matrix);
    
            moblieLeng = offset*2  + bmpW;// 两个相邻页面的偏移量
    
        }
    
    /这个方法在
    viewpager.setOnPageChangeListener(new OnPageChangeListener() {
    
                @Override
                public void onPageSelected(int postion) {
                    
                    animation(postion);
                }
    使用
    private void animation(int postion) {
            Animation animation = new TranslateAnimation(currIndex * moblieLeng, postion * moblieLeng, 0, 0);// 平移动画
            currIndex = postion;
            animation.setFillAfter(true);// 动画终止时停留在最后一帧,不然会回到没有执行前的状态
            animation.setDuration(200);// 动画持续时间0.2秒
            image.startAnimation(animation);// 是用ImageView来显示动画的
        }
        
    
    121) 利用ContentProvider扫描手机中所有图片
    
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    
     private void getReasourcePic() {
    
            // 判断sd卡是否可用
            if (!Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, "当前存储卡不可用!", Toast.LENGTH_LONG).show();
                return;
            }
    
            // ProgressDialog mProgressDialog = ProgressDialog.show(this, null,
            // "正在加载....");
    
            // 开启线程扫描
            new Thread() {
                public void run() {
    
                    // 所有图片的url
                    Uri mImgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    
                    ContentResolver cr = MainActivity.this.getContentResolver();
    
                    // 根据图片更改的时间排序获取图片
                    Cursor cursor = cr.query(mImgUri, null,
                            MediaStore.Images.Media.MIME_TYPE + " =? or "
                                    + MediaStore.Images.Media.MIME_TYPE + " =? ",
                            new String[] {"image/jpeg","image/png"},
                            MediaStore.Images.Media.DATE_MODIFIED);
    
                    Set<String> mDirPaths = new HashSet<String>(); // 防止重复遍历使用的集合
                                                                    // 获取的文件可能会都在一个文件夹下
    
                    while (cursor.moveToNext()) {
                        // 获取图片路径
                        String path = cursor.getString(cursor
                                .getColumnIndex(MediaStore.Images.Media.DATA));
                        // 根据图片的路径获取文件夹
                        File parentFile = new File(path).getParentFile();
                        if (parentFile == null)
                            continue;
    
                        // 获取文件夹的路径
                        String dirPath = parentFile.getAbsolutePath();
    
                        // 集合中是否存在该文件夹
                        if (mDirPaths.contains(dirPath)) {
                            continue;
                        } else {
    
                            mDirPaths.add(dirPath); // 不存在就放入集合中
                            // bean.setDir(dirPath);
                            // bean.setFirstImagePath(path);
    
                            Log.i("TAG", dirPath);
    
                        }
    
                        if (parentFile.list() == null)
                            continue;
    
                        // 获取文件夹下图片的数量
                        int picSize = parentFile.list(new FilenameFilter() {
    
                            @Override
                            public boolean accept(File dir, String filename) {
                                if (filename.endsWith(".jpg")
                                        || filename.endsWith(".jpeg")
                                        || filename.endsWith(".png"))
                                    return true;
    
                                return false;
                            }
                        }).length;
    
                        // bean.setCount(picSize); //文件夹下图片的数量
    
                        // if(picSize > mMaxCount){
                        // mMaxCount = picSize;
                        // mCurrentDir=parentFile;
                        // }
    
                    }
                    cursor.close();
    
                };
            }.start();
        }
    
    122) 点击Listview的item项,没有反应问题
        点击每一个item的时候没有反应,无法获取的焦点。原因多半是由于在你自己
        定义的Item中存在诸如ImageButton,Button,CheckBox等子控件,他们获取了
        焦点,
        所以定义viewGroup和其子控件两者之间的关系:
          android:descendantFocusability
          beforeDescendants:viewgroup会优先其子类控件而获取到焦点
          afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
          blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
    
    
    123)如果当前activity的启动模式是singleTask...则它上个界面给它传来的bundle都不能接收到
    
    124)单例模式模板
         public class ImageLoader {
        
        private static ImageLoader mInstance;
    
        public ImageLoader() {
        }
        
        public static ImageLoader getInstance(){
            if(mInstance==null){
                //当两个线程同时到达时,同步处理
                synchronized (ImageLoader.class) {
                    if(mInstance==null){
                        mInstance=new ImageLoader();
                    }
                }
            }
            return mInstance;
        }
    
    }
    
    125) 在组件四周添加图片的方法
        xml中使用:android:drawableBottom
        代码中使用:setCompoundDrawablesWithIntrinsicBounds()和setCompoundDrawablesWithIntrinsicBounds。
    
    
    126)选择器属性详解
    android:state_pressed       如果是true,当被点击时显示该图片,如果是false没被按下时显示默认
    android:state_focused       true,获得焦点时显示;false,没获得焦点显示默认
    android:state_hovered       光标是否悬停,通常与focused state相同,它是4.0的新特性
    android:state_selected      true,当被选择时显示该图片;false,当未被选择时显示该图片。
    android:state_checkable     true,当CheckBox能使用时显示该图片;false,当CheckBox不能使用时显示该图片。
    android:state_checked       true,当CheckBox选中时显示该图片;false,当CheckBox为选中时显示该图片。
    android:state_enabled       true,当该组件能使用时显示该图片;false,当该组件不能使用时显示该图片。
    android:state_activated     被激活(这个麻烦举个例子,不是特明白)
    android:state_window_focused true,当此activity获得焦点在最前面时显示该图片;false,当没在最前面时显示该图片
    
    
    127) seekBar组件的样式
       
    <SeekBar
            android:id="@+id/view_seekBar"
            android:layout_width="260dp"
            android:layout_height="wrap_content"
            android:progressDrawable="@drawable/seekbar_style"
            android:thumb="@null" />
    
    seekbar_style.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <item android:id="@android:id/background">
            <shape>
                <corners android:radius="5dip" />
    
                <gradient
                    android:angle="270"
                    android:centerColor="#EBEBEB"
                    android:centerY="0.75"
                    android:endColor="#EBEBEB"
                    android:startColor="#EBEBEB" />
            </shape>
        </item>
        <item android:id="@android:id/secondaryProgress">
            <clip>
                <shape>
                    <corners android:radius="5dip" />
    
                    <gradient
                        android:angle="270"
                        android:centerColor="#80ffb600"
                        android:centerY="0.75"
                        android:endColor="#a0ffcb00"
                        android:startColor="#80ffd300" />
                </shape>
            </clip>
        </item>
        <item android:id="@android:id/progress">
            <clip>
                <shape>
                    <corners android:radius="5dip" />
    
                    <gradient
                        android:angle="270"
                        android:centerColor="@color/main_color"
                        android:centerY="0.75"
                        android:endColor="@color/main_color"
                        android:startColor="@color/main_color" />
                </shape>
            </clip>
        </item>
    
    </layer-list>
    
    
    128) 给PopupWindow设置动画效果
        从上到下,从下到上
    mDirPopupWindow.setAnimationStyle(R.style.dir_popup_anim);
    
        <style 
            name="dir_popup_anim">
            <item name="android:windowEnterAnimation">@anim/side_up</item>
            <item name="android:windowExitAnimation">@anim/side_down</item>
        </style>
    
    side_up.xml
    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate 
            android:duration="200"
            android:fromXDelta="0"
            android:fromYDelta="100%"
            android:toXDelta="0"
            android:toYDelta="0"/>
    </set>
    
    
    side_down.xml
    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate 
            android:duration="200"
            android:fromXDelta="0"
            android:fromYDelta="0"
            android:toXDelta="0"
            android:toYDelta="100%"/>
    
    </set>
    
    129) 16进制颜色设置
     格式如#00FFFFFF,前两位代表不透明度的十六进制。00表示完全透明,FF就是全不透明
            100% — FF
            95% — F2
            90% — E6
            85% — D9
            80% — CC
            75% — BF
            70% — B3
            65% — A6
            60% — 99
            55% — 8C
            50% — 80
            45% — 73
            40% — 66
            35% — 59
            30% — 4D
            25% — 40
            20% — 33
            15% — 26
            10% — 1A
            5% — 0D
            0% — 00 
    
     
    130) 在一个程序中启动另一个程序
        1.知道了另一个应用的包名和MainActivity的名字之后便可以直接通过如下代码来启动:
            Intent intent = new Intent(Intent.ACTION_MAIN); 
            intent.addCategory(Intent.CATEGORY_LAUNCHER);             
            ComponentName cn = new ComponentName(packageName, className);             
            intent.setComponent(cn); 
            startActivity(intent); 
        2.一般都不知道应用程序的启动Activity的类名,而只知道包名,我们可以通过ResolveInfo类来取得启动Acitivty的类名
    
    
    131) 让自己的应用也成为系统照相机
    
        仅需在注册文件夹主动类下,新增一个拦截器:
            <intent-filter>
                    <action android:name="android.media.action.IMAGE_CAPTURE"/>
                    <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
    
    132) 存放数据到sd卡,不同方法的区别
        应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的。
        大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中。
        这样当该应用被卸载后,这些数据还保留在SDCard中,留下了垃圾数据。
    
         Context.getExternalFilesDir():一般放一些长时间保存的数据 SDCard/Android/data/你的应用的包名/files/ 目录
         Context.getExternalCacheDir():一般存放临时缓存数据 SDCard/Android/data/你的应用包名/cache/目录
         如果使用上面的方法,当你的应用在被用户卸载后,SDCard/Android/data/你的应用的包名/ 这个目录下的所有文件都会被删除,不会留下垃圾信息。
         上面二个目录分别对应 设置->应用->应用详情里面的”清除数据“与”清除缓存“选项
    
    133) activity系统自动动画
          overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); //淡入淡出的效果
          overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right); //由左向右滑入的效果
    
    
    134) 动态创建组件到布局
    
            ListView listView=new ListView(this);
            LinearLayout.LayoutParams param=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            listView.setBackgroundColor(Color.BLACK);
            
            parentLayou.addView(listView,param);
    
    135)判断耳机孔是否被插入
    AudioManager localAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
    localAudioManager.isWiredHeadsetOn()   如果插入了耳机,就返回true,否则false;
    权限
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    
    
    136) Radiogroup中的radioButton都不可编辑方法
        RadioButton.setClickable(false);
    
    
    137) 防止按钮连续点击
       public class CommonUtils {
    
        private static long lastClickTime;
        
        public synchronized static boolean isSlowClick() {
            long time = System.currentTimeMillis();
            if (time - lastClickTime < 1500) {
                return false;
            }
            lastClickTime = time;
            return true;
        }
    }
    
    if(CommonUtils.isSlowClick()){
    }
    
    
    138) 系统默认参数
    Android平台定义了三种字体大小:
    
        "?android:attr/textAppearanceLarge"
        "?android:attr/textAppearanceMedium"
        "?android:attr/textAppearanceSmall"
    
    Android字体颜色:
    
        android:textColor="?android:attr/textColorPrimary"
        android:textColor="?android:attr/textColorSecondary"
        android:textColor="?android:attr/textColorTertiary"
        android:textColor="?android:attr/textColorPrimaryInverse"
        android:textColor="?android:attr/textColorSecondaryInverse"
    
    分隔符
    
    横向:
    
    <View
        android:layout_width="fill_parent"
        android:layout_height="1dip"
        android:background="?android:attr/listDivider" />
    
    
    纵向:
    
    <View   android:layout_width="1dip"
        android:layout_height="fill_parent"
        android:background="?android:attr/listDivider" />
    
    
    139) 去除默认GridView的边距
    
       android:listSelector="@null"  使用这个可去除边距
    
    140) dp和px直接转换方法
         public static float applyDimension(int unit, float value,
                                           DisplayMetrics metrics)
        {
            switch (unit) {
            case TypedValue.COMPLEX_UNIT_PX:
                return value;
            case COMPLEX_UNIT_DIP:
                return value * metrics.density;
            case COMPLEX_UNIT_SP:
                return value * metrics.scaledDensity;
            case COMPLEX_UNIT_PT:
                return value * metrics.xdpi * (1.0f/72);
            case COMPLEX_UNIT_IN:
                return value * metrics.xdpi;
            case COMPLEX_UNIT_MM:
                return value * metrics.xdpi * (1.0f/25.4f);
            }
            return 0;
        }
    
    
    141) style添加自定义组件属性值
        自定义属性在styles.xml中都不需要命名空间可以直接用属性名就可以了
    
        <style name="input_myedit_style">
            <item name="android:layout_width">match_parent</item>
            <item name="android:layout_height">wrap_content</item>
            <item name="titlewidth">@dimen/survery_titlewidth</item> 
        </style>
        
      
    
    142) Fragment使用方法
          onCreateView() 方法中只进行组件的初始化
            if (view == null) {
                view = inflater.inflate(R.layout.hello, null);
            }
    
          在 onStart() 中初始化数据
    
    143) list 的 遍历方式
         
    
    
    144) 使用系统相机和系统相册获取图片
          (1)相机获取图片
             打开系统相机:
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"image.jpg"));
                //指定照片保存路径(SD卡),image.jpg为一个临时文件,每次拍照后这个图片都会被替换
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(openCameraIntent, TAKE_PICTURE);
    
             在回调中获取图片:
                 Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/image.jpg");
                 iv_image.setImageBitmap(newBitmap);
              
           (2)系统相册获取图片:
               打开系统相册:
               Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                openAlbumIntent.setType("image/*");
               startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
    
              在回调中获取图片:
                  ContentResolver resolver = getContentResolver();
                  //照片的原始资源地址
                  Uri originalUri = data.getData(); 
                  try {
                    //使用ContentProvider通过URI获取原始图片
                    Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                    if (photo != null) {
                        iv_image.setImageBitmap(smallBitmap);
                    }
             
            (3)修剪图片
                 public void startPhotoZoom(Uri uri) {
                     Intent intent = new Intent("com.android.camera.action.CROP");
                     intent.setDataAndType(uri, "image/*");
                    // 设置裁剪
                    intent.putExtra("crop", "true");
                    // aspectX aspectY 是宽高的比例
                    intent.putExtra("aspectX", 1);
                    intent.putExtra("aspectY", 1);
                    // outputX outputY 是裁剪图片宽高
                    intent.putExtra("outputX", 340);
                    intent.putExtra("outputY", 340);
                    intent.putExtra("return-data", true);
                    startActivityForResult(intent, RESULT_REQUEST_CODE);
            
                }
    
                保存裁剪之后的图片数据
                private void getImageToView(Intent data) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap photo = extras.getParcelable("data");
                        Drawable drawable = new BitmapDrawable(this.getResources(), photo);
                        iv_photo.setImageDrawable(drawable);
                    }
                }
    
     145) 将图片保存到sd卡文件夹下后,图库无法显示的问题
     /**
          *  使用照相机 保存图片到文件夹下,刷新图库
          * @param context
          * @param path
          */
         public static void galleryAddPic(Context context, String path) {  
                Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);  
                File f = new File(path);  
                Uri contentUri = Uri.fromFile(f);  
                mediaScanIntent.setData(contentUri);  
                context.sendBroadcast(mediaScanIntent);    //要想看的该图片要进行广播
            }  
    
      146) listview中的一些常见大坑
           (1)ViewHolder 是内部类,所以最好用静态的
                   static class ViewHolder {。。。}
           (2)数据错乱:
                  holder.view_name .setTag(holder.view_name.toString());
                  if(holder.view_name.getTag().equals(holder.view_name.toString())){
                     holder.view_gender .setMyEditViewClik(this, R.id.view_gender);
                  }
    
      147) Handler的静态使用
    
            handler = new MyHandler(this);
    
        static class MyHandler extends Handler{
    
            WeakReference<UpdateService> weakRef;
    
            MyHandler(UpdateService updateService){
                weakRef = new WeakReference<>(weakRefItem);
            }
    
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                EcgGatherActivityBase activity = activityRef.get();
    
                if(activity == null){
                    return;
                }
                switch (msg.arg1){
                    case SAVEFINISH:
                        MCToast.show(R.string.common_save_success, activity);
                        activity.finish();
                        break;
                    default:
                        break;
                }
            }
        }
    
    
    148)  网络连接超时设置
    
    HttpParams httpParameters = new BasicHttpParams();  
    HttpConnectionParams.setConnectionTimeout(httpParameters, 3000); //设置连接超时 
    HttpConnectionParams.setSoTimeout(httpParameters, 3000); //设置请求超时 
      
    HttpClient client = new DefaultHttpClient(httpParameters); 
    HttpGet mothod = new HttpGet(jasonUrl); 
      
    HttpResponse httpResponse = client.execute(mothod); 
    
    
    149) List 去除元素的方法
          if (subList.indexOf(subScribe) >= 0){
          subList.remove(subScribe);
           }
    
    150) 流转转化成字符串
    public static String inputStream2String(InputStream is)  {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i = -1;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            return baos.toString();
        }
    

    相关文章

      网友评论

          本文标题:常用方法3

          本文链接:https://www.haomeiwen.com/subject/ubxlqxtx.html