wen742538485 发表于 2013-1-30 04:12:26

Android有用代码片段(二)

二十一、获取手机屏幕分辨率
view plaincopy
DisplayMetricsdm = new DisplayMereics();

      getWindowManager().getDefaultDisplay().getMetrics(dm);

      float width = dm.widthPixels * dm.density;

      float height = dm.heightPixels * dm.density
    在这里问什么要乘以dm.density   了,是因为通过dm.widthPixels的到的结果始终是320,不是真实的屏幕分辨率,所以要乘以dm.density得到真实的分辨率。
   二十二、在Activity里面播放背景音乐
view plaincopy
public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.mainlay);
             mediaPlayer = MediaPlayer.create(this, R.raw.mu);
             mediaPlayer.setLooping(true);
             mediaPlayer.start();

                   }

      二十三、让程序的界面不随机器的重力感应而翻转
               第一种方法,在manifast文件里面
view plaincopy
<activity
android:screenOrientation="portrait">
</activity>

               第二种,在代码里面
view plaincopy
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    二十四、使activity全屏显示
view plaincopy
requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,      
                WindowManager.LayoutParams. FLAG_FULLSCREEN);

      二十五、在RelativeLayout中使selector要注意点


         关于selector的使用方法,可以参考http://blog.csdn.net/aomandeshangxiao/article/details/6759576这篇文章,今天,遇到在RelativeLayout中添加background为selector后没有反应的问题,寻摸了很长时间,一直没有找到原因,其实只要加上一句代码就完全可以解决:


view plaincopy
<span style="font-size:16px;">RelativeLayout 里面加上android:clickable="true"</span>

这样,RelativLayout就会出现在selector里面定义的效果。

   二十六、显示或隐藏虚拟键盘
view plaincopy
显示:
InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

隐藏:
InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);

   二十七、退出程序时清除通知中信息


view plaincopy
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.cancelAll();

   二十八、创建快捷方式


view plaincopy
Intent intent=new Intent();
//设置快捷方式的图标
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));
//设置快捷方法的名称
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "点击启动哥的程序");            //设置点击快键图标的响应操作
view plaincopy
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));
//传递Intent对象给系统
setResult(RESULT_OK, intent);
finish();


   二十九、获取文件中的类名:


view plaincopy
String path = context.getPackageManager().getApplicationInfo(
                                        context.getPackageName(), 0).sourceDir;
                        DexFile dexfile = new DexFile(path);
                        Enumeration<String> entries = dexfile.entries();
                        while (entries.hasMoreElements()) {
                              String name = (String) entries.nextElement();
                              ......
                        }



三十. TextView中的getTextSize返回值是以像素(px)为单位的,

而setTextSize()是以sp为单位的.

所以如果直接用返回的值来设置会出错,解决办法是:

用setTextSize()的另外一种形式,可以指定单位:

view plaincopy
TypedValue.COMPLEX_UNIT_PX : Pixels   
TypedValue.COMPLEX_UNIT_SP : Scaled Pixels   
TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
三十一. 在继承自View时,绘制bitmap时,需要将图片放到新建的drawable-xdpi

中,否则容易出现绘制大小发生改变



三十二. 在文字中加下划线: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);



三十三. scrollView是继承自frameLayout,所以在使用LayoutParams时需要用frameLayout的



三十四、android阴影字体设置



view plaincopy
<TextViewandroid:id="@+id/tvText1"   
android:layout_width="wrap_content"   
android:layout_height="wrap_content"   
android:text="text1"   
android:textSize="30sp"   
android:textStyle="bold"   
android:textColor="#FFFFFF"   
android:shadowColor="#ff0000ff"
android:shadowDx="5"
android:shadowDy="5"      
android:shadowRadius="10"/>



android:shadowColor 阴影颜色

android:shadowDx 阴影的水平偏移量

android:shadowDy 阴影的垂直偏移量

android:shadowRadius 阴影的范围



为了统一风格和代码的复用,通常可以把这个样式抽取放入到style.xml文件中

view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="textstyle">         
      <item name="android:shadowColor">#ff0000ff</item>
      <item name="android:shadowRadius">10</item>
      <item name="android:shadowDx">5</item>
      <item name="android:shadowDy">5</item>      
    </style>
</resources>
view plaincopy
<TextView
      style="@style/textstyle"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="字体样式"
      android:textSize="30sp"
      android:textStyle="bold" />


三十五、android实现手机震动功能


view plaincopy
import android.app.Activity;
import android.app.Service;
import android.os.Vibrator;

public class TipHelper {   
    public static void Vibrate(final Activity activity, long milliseconds) {
      Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
      vib.vibrate(milliseconds);
    }
    public static void Vibrate(final Activity activity, long[] pattern,boolean isRepeat) {
      Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
      vib.vibrate(pattern, isRepeat ? 1 : -1);
    }
}


还需要在AndroidManifest.xml 中添加震动权限:
view plaincopy
<uses-permission android:name="android.permission.VIBRATE" />
通过上面操作,我们可以使用TipHelper所定义的函数了。两个Vibrate函数的参数简单介绍如下:
final Activity activity:调用该方法的Activity实例

long milliseconds :震动的时长,单位是毫秒

long[] pattern    :自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒

boolean isRepeat : 是否反复震动,如果是true,反复震动,如果是false,只震动一次

三十六、常用的正则表达式


       ^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$    //email地址
       ^+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$  //url
       ^(d{2}|d{4})-((0({1}))|(1))-((({1}))|(3))$ //年-月-日
       ^((0({1}))|(1))/((({1}))|(3))/(d{2}|d{4})$//月/日/年
       ^(+)@(([{1,3}.{1,3}.{1,3}.)|((+.)+))({2,4}|{1,3})(]?)$   //Emil
       ^((\+?{2,4}\-{3,4}\-)|({3,4}\-))?({7,8})(\-+)?$   //电话号码
       ^(d{1,2}|1dd|2d|25).(d{1,2}|1dd|2d|25).(d{1,2}|1dd|2d|25).(d{1,2}|1dd|2d|25)$   //IP地址

       (^\s*)|(\s*$)   // 首尾空格

       ^{4,15}$// 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线)

       ^**$//腾讯QQ号

三十七、输入框不挤压activity布局:

在manifest文件activity下 加:


view plaincopy
android:windowSoftInputMode="adjustPan"

三十八、listview中item中button可点击:


view plaincopy
android:descendantFocusability="blocksDescendants"

三十九、获取移动设备的IP地址:


view plaincopy
public class Tools {
    public static String getLocalIpAddress() {   
      try {   
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {   
                NetworkInterface intf = en.nextElement();   
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {   
                  InetAddress inetAddress = enumIpAddr.nextElement();   
                  if (!inetAddress.isLoopbackAddress()) {   
                        return inetAddress.getHostAddress().toString();   
                  }   
                }   
            }   
      } catch (SocketException ex) {   
            Log.e("出错啦", ex.toString());   
      }   
      return null;   
    }   
}
然后
      WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
      WifiInfo wi = wm.getConnectionInfo();
      System.out.println("IP地址是:"+Tools.getLocalIpAddress());
      System.out.println("SSID:"+wi.getSSID());
最后记得加两个权限
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
页: [1]
查看完整版本: Android有用代码片段(二)