Android有用代码片断(五)

不知不觉中,就收集了超过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; @Override public 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里用的Tag kl.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里用的Tag wl.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 block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }


post:

HttpClient httpClient = null null; HttpPost httpRequest = null null; HttpResponse httpResponse = null null; try { httpUrl = "http://192.168.1.7:8080/exa/index.jsp"; // 取得默认的 HttpClient httpClient = new DefaultHttpClient(); // HttpPost 连接对象 httpRequest = new HttpPost(httpUrl); // 使用 NameValuePair 来保存要传递的 Post 参数 List<NameValuePair> params = new ArrayList<NameValuePair>(); // 添加要传递的参数 new params.add(new BasicNameValuePair("testParam1", "110")); // 设置字符集 HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312"); // 请求 httpRequest httpRequest.setEntity(httpentity); // 取得 HttpResponse httpResponse = 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); } } } //在原始文本中提取@用户名 方式的文字出来,加上自定义的tag public 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文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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定义的是圆角
布局中:

1
2
3
4
<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.全局字体大小缩放发生改变












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值