不知不觉中,就收集了超过70条的自己感觉有意思的代码片段,分为三篇文章:android有用代码片段、Android有用代码片段(二)、Android有用代码片段(三)、Android有用代码片段(四)这三篇,今天,开始第五篇的整理!这里解释一下,因为一、二、三都是每个有20个片段,但是在四中,由于第70个代码过长,所以在第四篇中,只有10个片段。


七十一、android自动跳转

有些时候需要类似这样的功能,在一个页面停留2秒后,跳转到另外一个页面!

第一种方法:

Timer timer = new Timer();TimerTask timerTask = new TimerTask() {               @Override        public void run() {                // 你要干的活                       }};timer.schedule(timerTask, 1000 * 2); //2秒后执行

在run()方法里面写上你的跳转就可以了。

第二种方法:

private final int SPLASH_DISPLAY_LENGHT = 2000;        @Override        public void onCreate(Bundle savedInstanceState) {                super.onCreate(savedInstanceState);                this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                  WindowManager.LayoutParams.FLAG_FULLSCREEN);                  setContentView(R.layout.splash);                new Handler().postDelayed(new Runnable() {                        @Override                        public void run() {                                Intent intent = new Intent(Splash.this, XXX.class);                                Splash.this.startActivity(intent);                                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);                                Splash.this.finish();                        }                }, SPLASH_DISPLAY_LENGHT);        }

使用handler延迟2秒后跳转。


七十二、Gally选中高亮状态

没有选中,在GalleryActivity中,设置gallery.setUnselectedAlpha(0.3f); 透明度为0.3

选中,在ImageAdapter的getView(int position, View convertView, ViewGroup parent)中,设置imageview.setBackgroundColor(Color.alpha(1)); 背景色为1

七十三、TextView颜色设置

android:textColor                    //设置文本颜色android:textColorHighlight           //被选中文字的底色,默认为蓝色android:textColorHint                //设置提示信息文字的颜色,默认为灰色。与hint一起使用。


七十四、Button使用Shape

<?xml version="1.0" encoding="utf-8"?><selector    xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true" >        <shape>            <gradient                android:startColor="#ff8c00"                android:endColor="#FFFFFF"                android:angle="270" />            <stroke                android:width="2dp"                android:color="#dcdcdc" />            <corners                android:radius="2dp" />            <padding                android:left="10dp"                android:top="10dp"                android:right="10dp"                android:bottom="10dp" />        </shape>    </item>     <item android:state_focused="true" >        <shape>            <gradient                android:startColor="#ffc2b7"                android:endColor="#ffc2b7"                android:angle="270" />            <stroke                android:width="2dp"                android:color="#dcdcdc" />            <corners                android:radius="2dp" />            <padding                android:left="10dp"                android:top="10dp"                android:right="10dp"                android:bottom="10dp" />        </shape>    </item>     <item>              <shape>            <gradient                android:startColor="#ff9d77"                android:endColor="#ff9d77"                android:angle="270" />            <stroke                android:width="2dp"                android:color="#fad3cf" />            <corners                android:radius="2dp" />            <padding                android:left="10dp"                android:top="10dp"                android:right="10dp"                android:bottom="10dp" />        </shape>    </item></selector>

七十五、Android Drawable叠加处理方法

大家可能知道Bitmap的叠加处理在Android平台中可以通过Canvas一层一层的画就行了,而Drawable中如何处理呢? 除了使用BitmapDrawable的getBitmap方法将Drawable转换为Bitmap外,今天Android123给大家说下好用简单的LayerDrawable类,LayerDrawable顾名思义就是层图形对象。下面直接用一个简单的代码表示:

   Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);    Drawable[] array = new Drawable[3];      array[0] = new PaintDrawable(Color.BLACK); //黑色     array[1] = new PaintDrawable(Color.WHITE); //白色     array[2] = new BitmapDrawable(bm); //位图资源    LayerDrawable ld = new LayerDrawable(array); //参数为上面的Drawable数组        ld.setLayerInset(1, 1, 1, 1, 1);  //第一个参数1代表数组的第二个元素,为白色        ld.setLayerInset(2, 2, 2, 2, 2); //第一个参数2代表数组的第三个元素,为位图资源    mImageView.setImageDrawable(ld); 

上面的方法中LayerDrawable是关键,Android开发网提示setLayerInset方法原型为public void setLayerInset (int index, int l, int t, int r, int b) 其中第一个参数为层的索引号,后面的四个参数分别为left、top、right和bottom。对于简单的图片合成我们可以将第一和第二层的PaintDrawable换成BitmapDrawable即可实现简单的图片合成。


七十六、Android发信息时观察者

发信息大致的流程是:

观察者,ContentObserver

观察信息变化,它只能观察所有 就是 :Uri:content://sms/

你点击了发送按钮后,状态还是正在发送,这时这条信息已在你不注意时插入到发件箱中(调用 onChange一次,你可以查一下outbox的内容),当发送成功后(就会打发件箱的临时信息删除 又调用一次 onChange),成功后插入到已发信息sent(这是又会调用 onChange),它会调用三次,所以你们在观察发送信息时会出现onChange出现三次,这个解决方案我暂时只想到两种方案:

1:就是在contetnobserver类里定义一个变量 int count=0;     @Overridepublic void onChange(boolean selfChange) {  count++;//调用第三次才是已发信息  if(count==3){//代表发送了一条信息Log.i("wet", "发送了一条信息");count=0;//以便第下次用} 2:还有一个是:   记录  context.getContentResolver().query(Uri.parse("content://sms/sent"), null, null, null, null);首先记录它上次的条数然后再记录它这次的条数,如果改变了,那就代表它改变了

七十七、Android屏幕解锁和点亮屏幕

最近在做一个闹钟的项目,当闹钟响起的时候需要用到自动解锁和点亮屏幕,因此记录一下解屏幕锁与点亮屏幕的代码:

KeyguardManager  km= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); //得到键盘锁管理器对象KeyguardLock kl = km.newKeyguardLock("unLock"); //参数是LogCat里用的Tagkl.disableKeyguard(); //解锁PowerManager pm=(PowerManager) getSystemService(Context.POWER_SERVICE);//获取电源管理器对象PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tagwl.acquire();//点亮屏幕wl.release();//释放要实现自动解锁和点亮屏幕的功能则需要在AndroidManifest.xml添加权限:<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

七十八、去掉listView中间隔断线

方法1:listView.setDividerHeight(0); 方法2:this.getListView().setDivider(null);方法3:android:divider="@null"android:cacheColorHint="#00000000" 设置其为透明!! 默认为黑色!!!!!


七十九、仿iphone的icon的效果

public static Bitmap toRoundCorner(Bitmap bitmap, int pixels){Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), 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(Mode.SRC_IN));canvas.drawBitmap(bitmap, rect, rect, paint);return output;} 

八十、android背景图圆角等处理

public static Bitmap toRoundCorner(Bitmap bitmap, int pixels){Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), 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(Mode.SRC_IN));canvas.drawBitmap(bitmap, rect, rect, paint);return output;} 


八十一、http连接

String  httpUrl = "www.baidu.com"; HttpClient httpClient = new DefaultHttpClient();HttpGet httpRequest = new HttpGet(httpUrl);try {HttpResponse httpResponse =httpClient.execute(httpRequest);if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){String strResult = EntityUtils.toString(httpResponse.getEntity());}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}



post:

HttpClient httpClient = nullnull;HttpPost httpRequest = nullnull;HttpResponse httpResponse = nullnull;try {httpUrl = "http://192.168.1.7:8080/exa/index.jsp";// 取得默认的 HttpClienthttpClient = new DefaultHttpClient();// HttpPost 连接对象httpRequest = new HttpPost(httpUrl);// 使用 NameValuePair 来保存要传递的 Post 参数List<NameValuePair> params = new ArrayList<NameValuePair>();// 添加要传递的参数newparams.add(new BasicNameValuePair("testParam1", "110"));// 设置字符集HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");// 请求 httpRequesthttpRequest.setEntity(httpentity);// 取得 HttpResponsehttpResponse = httpClient.execute(httpRequest);// HttpStatus.SC_OK 表示连接成功if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 取得返回的字符串String strResult = EntityUtils.toString(httpResponse.getEntity());textView_1.setText(strResult);}} catch (Exception e) {e.printStackTrace();} finally {}


八十二、

android里图片下载工具类AsyncImageLoader分析

八十三、

Android 实现 按钮从两边移到中间动画效果


八十四、实现listview 飞入效果

private LayoutAnimationController getListAnim() {AnimationSet set = new AnimationSet(true);Animation animation = new AlphaAnimation(0.0f, 1.0f);animation.setDuration(300);set.addAnimation(animation);animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);animation.setDuration(500);set.addAnimation(animation);LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);return controller;}listView.setLayoutAnimation(getListAnim());


八十五Gallery只滑动一张照片

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {              return e2.getX() > e1.getX();          }                @Override          public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {              // e1是按下的事件,e2是抬起的事件              int keyCode;              if (isScrollingLeft(e1, e2)) {                  keyCode = KeyEvent.KEYCODE_DPAD_LEFT;              } else {                  keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;              }              onKeyDown(keyCode, null);              return true;          }  

重写的意思:把onFling里面的滑动转换为了点击物理左右方向键。


八十六、活动解锁

http://www.eoeandroid.com/thread-175883-1-1.html


八十七

在TextView中自定义链接

如果只是简单需要textview在显示时候将网址、邮件地址、电话号码识别出来并且带上超链接,只需要在xml将textview的属性添加一个autoLink="all"即可。但是如果希望在文字中定义更复杂的超链接,比如:点击特定文字后跳转到某个activity,则需要自定义Html类对于tag的解析方法。整个处理流程思路如下:

  1. TextView的文字使用带html tag的字符串,如:<a href=\"http://www.diandian.com\">android</a>其实并不难;
  2. 为要做除了网址链接、邮件链接、电话链接之外的超链接自己确定一个tag名字,加入到字符串中,如:<a href=\"http://www.diandian.com\">android</a>其实并不难<mention>哪里哪里</mention>;
  3. 自定义一个静态类,并且实现TagHandler接口,以识别自定义的tag类型

    public static class LinkHandler implements TagHandler    {               private int startIndex = 0;                  private int stopIndex = 0;        private Context ctx;                public LinkHandler(Context ctx)        {            super();            this.ctx=ctx;        }//识别自定义标签的起始和终止位置        public void handleTag(boolean opening, String tag, Editable output,                XMLReader xmlReader) {            if(tag.toLowerCase().equals(" mention"))            {                 if (opening) {                           startTxt(tag, output, xmlReader);                      } else {                          endTxt(tag, output, xmlReader);                      }            }        }                public void startTxt(String tag, Editable output, XMLReader xmlReader) {              startIndex = output.length();          }                public void endTxt(String tag, Editable output, XMLReader xmlReader) {              stopIndex = output.length();              output.setSpan(new TagSpan(output.toString().substring(startIndex,stopIndex)), startIndex, stopIndex,                          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);          }          //继承ClickableSpan类自定义类TagSpan实现OnClickListener接口,以此决定被识别出来的链接被点击后做什么        private class TagSpan extends ClickableSpan implements OnClickListener {                            String s;            public TagSpan(String s)            {                this.s=s;            }            @Override              public void onClick(View v) {                  // 跳转某页面,将自定义tag对应的文字参数传递过去                 NetActivity.pd.show();                getUid(s);            }         }            }//在原始文本中提取@用户名 方式的文字出来,加上自定义的tagpublic static String addTagsToString(String s)    {        //对@添加tag        Pattern p=Pattern.compile("@[\\S&&[^@]]+");        Matcher m=p.matcher(s);        while(m.find()){            s=s.replace(m.group(), "<mention>"+m.group()+"</mention>");        }                s="<a>"+s+"</a>"; //此处一定要在前后加上一个<a>标签,否则@用户名之后若还有文字,会被一起加入到mention标签之中,这个问题还没搞清楚是为什么,至少目前加上<a>标签后不会有问题        return s;    }



  4. 然后在activity中为textview设定文字
tv.setText(Html.fromHtml(addTagsToString(s),null,new LinkHandler(ctx)));
tv.setMovementMethod(LinkMovementMethod.getInstance())


八十八、

模仿通讯录按字母分类显示,汉字,英文自动按英文字母分类显示,滑动时用气泡显示最上面的汉字首字母提示,右侧字母栏点击快速定位


八十九listView Item里面存在Button

在button对应的view处加

android:focusable="false"android:clickable="false"android:focusableInTouchMode="false"
或者在 Item Layout的根控件设置其android:descendantFocusability=”blocksDescendants”


九十、自定义progressBar样式

在XML文件中分别定义进度条背景、第一进度颜色、第二进度颜色,然后在ProgressBar的android:progressDrawable属性应用即可。
先在drawable下建立progressbar_style.xml文件,内容如下:

1234567891011121314151617181920212223242526
<?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="5.0dip" />            <gradient android:startColor="#656666" android:endColor="#dbdedf" android:angle="270.0" android:centerY="0.75" android:centerColor="#bbbbbc" />        </shape>    </item>    <item android:id="@android:id/secondaryProgress">        <clip>            <shape>                <corners android:radius="8.0dip" />                <gradient android:startColor="#e71a5e" android:endColor="#6c213a" android:angle="90.0" android:centerY="0.75" android:centerColor="#ac6079" />            </shape>        </clip>    </item>    <item android:id="@android:id/progress">        <clip>            <shape>                <corners android:radius="8.0dip" />                <gradient android:startColor="#464647" android:endColor="#2d9ae7" android:angle="270.0" />            </shape>        </clip>    </item></layer-list>

分别定义背景,第一进度颜色,第二进度颜色
gradient是渐变,前面已经说过,corners定义的是圆角
布局中:

1234
<ProgressBar android:id="@+id/progressBar1" android:layout_width="fill_parent" android:layout_height="wrap_content"style="?android:attr/progressBarStyleHorizontal" android:progressDrawable="@drawable/progressbar_style"android:progress="50" android:max="100" android:secondaryProgress="70"></ProgressBar>

九十一、

android自定义ProgressBar(仿淘宝)的加载效果

九十二、

android仿微信的开门效果


九十三、Activity中ConfigChanges属性配置描述

“mcc” The IMSI mobile country code (MCC) has changed — that is, a SIM hasbeen detected and updated the MCC.移动国家号码,由三位数字组成,每个国家都有自己独立的MCC,可以识别手机用户所属国家。“mnc“ The IMSI mobile network code (MNC) has changed — that is, a SIM hasbeen detected and updated the MNC.移动网号,在一个国家或者地区中,用于区分手机用户的服务商。“locale“ The locale has changed — for example, the user has selected a new language that text should be displayed in.用户所在地区发生变化。“touchscreen“ The touchscreen has changed. (This should never normally happen.)“keyboard“ The keyboard type has changed — for example, the user has plugged in an external keyboard.键盘模式发生变化,例如:用户接入外部键盘输入。“keyboardHidden“ The keyboard accessibility has changed — for example, the user has slid the keyboard out to expose it.用户打开手机硬件键盘“navigation“ The navigation type has changed. (This should never normally happen.)“orientation“ The screen orientation has changed — that is, the user has rotated the device.设备旋转,横向显示和竖向显示模式切换。“fontScale“ The font scaling factor has changed — that is, the user has selected a new global font size.全局字体大小缩放发生改变 


"screenSize" The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
Added in API level 13.

当前可用的屏幕尺寸发生改变。这代表了一个改变目前可用大小,相对于当前的长宽比例,当用户横竖屏切换时会发生改变。然而,如果您的应用程序的API级别是12或更低,那么你的Activity会自己处理这个配置变化(在Android 3.2或更高的版本,这个配置更改不会重启你的activity)。

九十四、

android ---- ImageUtil工具类


九十五、判断wifi是否打开:

public boolean isWiFiActive() {              ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);              if (connectivity != null) {                  NetworkInfo[] infos = connectivity.getAllNetworkInfo();                  if (infos != null) {                      for(NetworkInfo ni : infos){                      if(ni.getTypeName().equals("WIFI") && ni.isConnected()){                          return true;                      }                  }              }              }              return false;          }   // .........  }  

2、

private boolean checkWifi() {      boolean isWifiConnect = true;      ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);  [java] view plaincopyprint?//check the networkInfos numbers  NetworkInfo[] networkInfos = cm.getAllNetworkInfo();  for (int i = 0; i<networkInfos.length; i++) {      if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) {         if(networkInfos[i].getType() == cm.TYPE_MOBILE) {             isWifiConnect = false;         }         if(networkInfos[i].getType() == cm.TYPE_WIFI) {             isWifiConnect = true;         }      }  }  return isWifiConnect;




更多相关文章

  1. Android SDK更新 Connection to http://dl-ssl.google.com refus
  2. RecyclerView 各种相关问题解决方法
  3. Android UI 中 gravity 与 layout_gravity 参数
  4. AndroidManifest中activity属性参数设置大全
  5. RelativeLayout参数意义
  6. android横竖屏切换参数
  7. Android基本控件常用属性及方法
  8. Android中一个Activity多个intent-filter的调用方法
  9. Android模拟SD卡实现方法解析

随机推荐

  1. android四种动画
  2. Android L下载
  3. Android中数据存储的三种方式--基础
  4. Android: 模拟器system分区没有可用空间
  5. 关于微信登陆报错的解决方法 Caused by:
  6. 腾讯微博java(android) api
  7. android 数据储存——--文件存储(2)
  8. Android仿人人客户端(v5.7.1)——网络模块
  9. android studio + ndk + cmake + jna +sq
  10. 安卓Android手机系统内文件夹目录解释