3.3.代码

1 显示图片所使用的uri:

String imageUri = "http://site.com/image.png"; // from Web
String imageUri = "file:///mnt/sdcard/image.png"; // from SD card
String imageUri = "content://media/external/audio/albumart/13"; // from content provider
String imageUri = "assets://image.png"; // from assets
String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)
注意:使用drawable://除非你真的需要他。时刻要注意使用本地图片加载方法:setImageResource带代替ImageLoader。

2 监听网络变化

系统常量:ConnectivityManager.CONNECTIVITY_ACTION action : "android.net.conn.CONNECTIVITY_CHANGE"

 //在Androidmanifest中加入
 //<uses-permission android:name="android.permission.ACCESS_NETWOR
// 注册网络监听广播
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
mContext.registerReceiver(mNetWorkChangeReceiver, intentFilter);

3 Toast消息框重复提示

      //解决思路:判空处理
      private Toast mToast;  
      public void showToast(String text) {    
          if(mToast == null) {    
              mToast = Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT);    
          } else {    
              mToast.setText(text);      
              mToast.setDuration(Toast.LENGTH_SHORT);    
          }    
          mToast.show();    
      }    

      //SuperToast 类库 使用避免重复  
      if (mSuperToast!=null){
               mSuperToast.setText("message:"+count);
               mSuperToast .setDuration(AttributeUtils.getDuration(getActivity()));
               mSuperToast .setFrame(AttributeUtils.getFrame(getActivity()));
               mSuperToast .setColor(AttributeUtils.getColor(getActivity()));
               mSuperToast .setAnimations(AttributeUtils.getAnimations(getActivity()));
            }else{
               mSuperToast= new SuperToast(getActivity());
               mSuperToast.setText("SuperToast" + count);
               mSuperToast .setDuration(AttributeUtils.getDuration(getActivity()));
               mSuperToast .setFrame(AttributeUtils.getFrame(getActivity()));
               mSuperToast .setColor(AttributeUtils.getColor(getActivity()));
               mSuperToast .setAnimations(AttributeUtils.getAnimations(getActivity()));
              // mSuperToast  .setColor(AttributeUtils.getColor(getActivity()));
           }
            mSuperToast.cancelAllSuperToasts();
            mSuperToast.show();

参考文献 android 关于Toast重复显示解决方法

4 TextView加粗字体

//在代码中设置:  
TextView tv = (TextView)findViewById(R.id.tv); 
TextPaint tp = tv.getPaint(); 
tp.setFakeBoldText(true); 
//在xml中设置
android:textStyle="bold"

5 监听Back键按下事件

  /** 
     * 监听Back键按下事件,方法1: 
     * 注意: 
     * super.onBackPressed()会自动调用finish()方法,关闭 
     * 当前Activity. 
     * 若要屏蔽Back键盘,注释该行代码即可 
     */  
    @Override  
    public void onBackPressed() {  
        super.onBackPressed();  
        System.out.println("按下了back键   onBackPressed()");         
    }  


 /** 
    * 监听Back键按下事件,方法2: 
    * 注意: 
    * 返回值表示:是否能完全处理该事件 
    * 在此处返回false,所以会继续传播该事件. 
    * 在具体项目中此处的返回值视情况而定. 
    */  
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {  
             System.out.println("按下了back键   onKeyDown()");  
             return false;  
        }else {  
            return super.onKeyDown(keyCode, event);  
        }  

    }  

6 判断Activity属于任务栈中

      /**
 * 判断是否存在Activity
 *
 * @param context     上下文
 * @param packageName 包名
 * @param className   activity全路径类名
 * @return {@code true}: 是<br>{@code false}: 否
 */
public static boolean isActivityExists(Context context, String packageName, String className) {
    Intent intent = new Intent();
    intent.setClassName(packageName, className);
    return !(context.getPackageManager().resolveActivity(intent, 0) == null ||
            intent.resolveActivity(context.getPackageManager()) == null ||
            context.getPackageManager().queryIntentActivities(intent, 0).size() == 0);
}

7 ActionBar 返回键处理

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) { 
    case android.R.id.home://关键代码
       onBackPressed();
    break;
  }
   return true;
}

8 RecycleView加载更多

   //原始分页
  /*  mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        private boolean loading = true;
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visible  = layoutManager.getChildCount();
            int total = layoutManager.getItemCount();
            int past=layoutManager.findFirstCompletelyVisibleItemPosition();
            if (loading) {
            //previousTotal 未全局变量
                if (total > previousTotal) {
                    loading = false;
                    previousTotal = total;
                }
            }
            if (!loading&&((visible + past) >= total)){
                Log.d("mRecyclerView", "visible:" + visible + " past:" + past + " total:" + total
                        +" previousTotal:"+ previousTotal+" loading:"+loading);
                mPage++;
                startSearch();
                loading = true;
            }
        }
    });*/    

9 EditText获取焦点状态

   EditText searchView = (EditText)findViewById(R.id.search_text);
   searchView.setOnFocusChangeListener(new android.view.View.
    OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if (hasFocus) {
        // 此处为得到焦点时的处理内容
    } else {
        // 此处为失去焦点时的处理内容
    }
}});    

10 SD卡总容量

 public long getSDAllSize(){  
 //取得SD卡文件路径  
 File path = Environment.getExternalStorageDirectory();   
 StatFs sf = new StatFs(path.getPath());   
 //获取单个数据块的大小(Byte)  
 long blockSize = sf.getBlockSize();   
 //获取所有数据块数  
 long allBlocks = sf.getBlockCount();  
 //返回SD卡大小  
 //return allBlocks * blockSize; //单位Byte  
 //return (allBlocks * blockSize)/1024; //单位KB  
 return (allBlocks * blockSize)/1024/1024; //单位MB  
 }     

11 SD卡剩余空间

 SD卡剩余空间
 public long getSDFreeSize(){  
 //取得SD卡文件路径  
 File path = Environment.getExternalStorageDirectory();   
 StatFs sf = new StatFs(path.getPath());   
 //获取单个数据块的大小(Byte)  
 long blockSize = sf.getBlockSize();   
 //空闲的数据块的数量  
 long freeBlocks = sf.getAvailableBlocks();  
 //返回SD卡空闲大小  
 //return freeBlocks * blockSize;  //单位Byte  
 //return (freeBlocks * blockSize)/1024;   //单位KB  
 return (freeBlocks * blockSize)/1024 /1024; //单位MB  
 }    

12 SD卡是否存在

private boolean ExistSDCard() {  
   if(android.os.Environment.getExternalStorageState()
   .equals(  
    android.os.Environment.MEDIA_MOUNTED)) {  
    return true;  
  } else  
   return false;  
 }

13 判断是否为合法IP

 /**
  * 判断是否为合法IP
  *
  * @return the ip
  */
public static boolean isIP(String ipAddress) {
  String ip ="((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?    \d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))";
  Pattern pattern = Pattern.compile(ip);
  Matcher matcher = pattern.matcher(ipAddress);
  return matcher.matches();
}           

14 获取手机可用内存和总内存:

private String[] getTotalMemory() {    
        String[] result = {"",""};  //1-total 2-avail    
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();      
        mActivityManager.getMemoryInfo(mi);      
        long mTotalMem = 0;    
        long mAvailMem = mi.availMem;    
        String str1 = "/proc/meminfo";    
        String str2;    
        String[] arrayOfString;    
        try {    
            FileReader localFileReader = new FileReader(str1);    
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);    
            str2 = localBufferedReader.readLine();    
            arrayOfString = str2.split("\\s+");    
            mTotalMem = Integer.valueOf(arrayOfString[1]).intValue() * 1024;    
            localBufferedReader.close();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
        result[0] = Formatter.formatFileSize(this, mTotalMem);    
        result[1] = Formatter.formatFileSize(this, mAvailMem);    
        Log.i(TAG, "meminfo total:" + result[0] + " used:" + result[1]);    
        return result;    
    }  

14 获取屏幕高度

      private void getWeithAndHeight(){    
        //这种方式在service中无法使用,    
        DisplayMetrics dm = new DisplayMetrics();    
        getWindowManager().getDefaultDisplay().getMetrics(dm);    
        String width = dm.widthPixels;              //宽    
        String height = dm.heightPixels;           //高    

        //在service中也能得到高和宽    
        WindowManager mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);    
        width = mWindowManager.getDefaultDisplay().getWidth();    
        height = mWindowManager.getDefaultDisplay().getHeight();    
      }          

15 获取屏幕密度

public static float getDensity(Context ctx) {

DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);

return metrics.density;

}

16 应用于View的获取控件实例

/**
  * 应用于View的获取控件实例
  * @param view
  * @param id
  * @return
  */
  @SuppressWarnings("unchecked")
 public static <T extends View> T $(View view, int id)   {
    return (T) view.findViewById(id);
 } 

17 应用于Activity的获取控件实例

    /**
     * 应用于Activity的获取控件实例
    *
     * @param activity
     * @param id
     * @return
    */
    @SuppressWarnings("unchecked")
    public static <T extends View> T $(Activity activity, int id) {
    return (T) activity.findViewById(id);
    }     

18 shouldOverrideUrlLoading(WebView view, String url)被废弃

 在Android N中 
 shouldOverrideUrlLoading(WebView view, String url)被废弃,
 改为shouldOverrideUrlLoading(WebView view, WebResourceRequest request),
 我们可以通过request.getUrl()来获取url。

 @Override
 public boolean shouldOverrideUrlLoading(WebView view,  WebResourceRequest request) {
return shouldOverrideUrlLoading(view,  request.getUrl().toString());
}

19 Android系统键盘显示隐藏监听,显示则隐藏,没有显示则弹出

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    通过判断高度来判断键盘状态

detailMainRL = (RelativeLayout) findViewById(R.id.home_news_detail_main_rl);
        detailMainRL.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener(){
            @Override
            public void onGlobalLayout()
            {

                int heightDiff = detailMainRL.getRootView().getHeight() - detailMainRL.getHeight();
                Log.v(TAG, "detailMainRL.getRootView().getHeight() = " + detailMainRL.getRootView().getHeight());
                Log.v(TAG, "detailMainRL.getHeight() = " + detailMainRL.getHeight());

                if (heightDiff > 100)
                { // 说明键盘是弹出状态
                    Log.v(TAG, "键盘弹出状态");
                    commentBoxRL.setVisibility(View.VISIBLE);
                } else{
                    Log.v(TAG, "键盘收起状态");
                    commentBoxRL.setVisibility(View.GONE);
                }
            }
        });                                                                                                                                                                           

20 Android ActionBar 菜单隐藏

    @Override  
    public boolean onPrepareOptionsMenu(Menu menu) {  
        Log.e("isMenuShuffle",isMenuShuffle + "");  
        if(isMenuShuffle)  
        {  
            menu.findItem(R.id.main_toolbar_shuffle).setVisible(true);  
        }else  
        {  
            menu.findItem(R.id.main_toolbar_shuffle).setVisible(false);  
        }  
        return super.onPrepareOptionsMenu(menu);  
    }  

21 PopupWindow 点击外部和返回键 消失处理 原理 详解

mPopupWindow=new PopupWindow(selectView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
mPopupWindow.setFocusable(false);
mPopupWindow.setOutsideTouchable(false);
// 这个是为了点击“返回Back”也能使其消失,并且并不会影响你的背景
mPopupWindow.setBackgroundDrawable(new BitmapDrawable());    
//本方法必须写在最后,否则会存在部分手机兼容问题  
  mPopupWindow.showAtLocation(findViewById(R.id.EditActivity_rootView), Gravity.BOTTOM,0,0);  

//date中compareTo的用法。也是比较时间大小的,相等返回0,大于返回1,小于返回-1.
public class Demo8 {
public static void main(String[] args) throws ParseException {
   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
   Date oldDate1 = format.parse("2012-05-12 15:16:00"); //这里时间可以自己定
   Date oldDate2 = format.parse("2011-05-12 15:16:00"); //这里时间可以自己定
   System.out.println(oldDate1.compareTo(oldDate2)); //判断,如果时间在这时间后,就执行后面操作
 }
}     

23 android 动态修改menu item的内容title

1)全局量:
MenuItem gMenuItem=NULL;

2)//创建菜单时keep
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu){
getMenuInflater().inflate(R.menu.menu, menu);
gMenuItem= menu.findItem(R.id.action_Seach);
return true;
}

3)需要时修改
//ANY PLACE
if(gMenuItem!=NULL){
gMenuItem.setTitle("Changed");
}

24 判断当前线程是否为主线程

  public boolean isMainThread() {
    return Looper.getMainLooper() == Looper.myLooper();
}

Last updated

Was this helpful?