以前工作中遇到的问题随笔

这篇文章主要是记录下以前遇到的一些问题和解决方法,有很多很可能已经过时了

1、Android 对于ListView拖动时变黑问题解决方法 

  用ListView显示一些String数据,发现如果不按住文字部分拖动ListView一切安好, 但是如果按住文字部分拖动的话所有文字部分都会变黑。
  解决方法其实很简单,问题的根源在于缓存颜色。方法有两个:

  1>在布局xml文件中的ListView中加入以下属性即可.
    android:cacheColorHint="#00000000"

  2>在代码中,对ListView使用setCacheColorHint方法。

    listView.setCacheColorHint(Color.TRANSPARENT);

    注意,在使用代码时,不能再使用lv.setBackgroundColor(Color.TRANSPARENT),将llistView的背景色设成透明,否则一样没有效果。

2、代码设置ListView的高度(用于解决ListView和ScrollView共存冲突的问题)

  1> 给ListView设固定高度,在代码中可以根据需要更改该高度值。

    注意:代码中设定ListView高度时,ListView高度=ListView项高度*ListView项数目+ListView分割线高度*(ListView项数目-1)

  public void setHeight()
  {
    ListAdapter listAdapter = list.getAdapter();
    if (listAdapter == null) {
      return;
    }
    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
      View listItem = listAdapter.getView(i, null, list);
      listItem.measure(0, 0);
      totalHeight += listItem.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = list.getLayoutParams();
    params.height = totalHeight + (list.getDividerHeight() * (listAdapter.getCount() - 1));
    // ((MarginLayoutParams)params).setMargins(10, 10, 10, 10);
    list.setLayoutParams(params);
  }

  2> 我们可以剔除ScrollView不用,而是采用这种思想:将ScrollView内希望显示的除ListView外的view,经过整理组合,最后添加成ListView的页眉或页脚显示。

3、打开系统已安装应用程序界面

  public class ClearCache {

    private static final String SCHEME = "package";
    /**
     * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.1及之前版本)
    */
    private static final String APP_PKG_NAME_21 = "com.android.settings.ApplicationPkgName";
    /**
     * 调用系统InstalledAppDetails界面所需的Extra名称(用于Android 2.2)
    */
    private static final String APP_PKG_NAME_22 = "pkg";
    /**
     * InstalledAppDetails所在包名
    */
    private static final String APP_DETAILS_PACKAGE_NAME = "com.android.settings";
    /**
     * InstalledAppDetails类名
    */
    private static final String APP_DETAILS_CLASS_NAME = "com.android.settings.InstalledAppDetails";
    /**
     * 调用系统InstalledAppDetails界面显示已安装应用程序的详细信息。 对于Android 2.3(Api Level
    * 9)以上,使用SDK提供的接口; 2.3以下,使用非公开的接口(查看InstalledAppDetails源码)。
    *
    * @param context
    *
    * @param packageName
    * 应用程序的包名
    */
    public static void showInstalledAppDetails(Context context, String packageName) {
      Intent intent = new Intent();
      final int apiLevel = Build.VERSION.SDK_INT;
      if (apiLevel >= 9) { // 2.3(ApiLevel 9)以上,使用SDK提供的接口
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        Uri uri = Uri.fromParts(SCHEME, packageName, null);
        intent.setData(uri);
      } else { // 2.3以下,使用非公开的接口(查看InstalledAppDetails源码)
      // 2.2和2.1中,InstalledAppDetails使用的APP_PKG_NAME不同。
        final String appPkgName = (apiLevel == 8 ? APP_PKG_NAME_22
                            : APP_PKG_NAME_21);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setClassName(APP_DETAILS_PACKAGE_NAME,
                          APP_DETAILS_CLASS_NAME);
        intent.putExtra(appPkgName, packageName);
      }
      context.startActivity(intent);
    }
  }

  调用示例

  ClearCache clearCache = new ClearCache();
  clearCache.showInstalledAppDetails(SettingActivity.this, "com.acme");

4、调用图库去选择并裁剪图片

  Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);

  intent.setType("image/*"); //这个参数是确定要选择的内容为图片

  intent.putExtra("crop", "circle"); //这个参数 不太懂,唯一知道的是:设置了参数,就会调用裁剪,如果不设置,就会跳过裁剪的过程。

  intent.putExtra("aspectX", 33); //这个是裁剪时候的 裁剪框的 X 方向的比例。

  intent.putExtra("aspectY",43); //同上Y 方向的比例. (注意: aspectX, aspectY ,两个值都需要为 整数,如果有一个为浮点数,就会导致比例失效。)

  //设置aspectX 与 aspectY 后,裁剪框会按照所指定的比例出现,放大缩小都不会更改。如果不指定,那么 裁剪框就可以随意调整了。

  intent.putExtra("outputX", 50); //返回数据的时候的 X 像素大小。

  intent.putExtra("outputY", 100); //返回的时候 Y 的像素大小。

  //以上两个值,设置之后会按照两个值生成一个Bitmap, 两个值就是这个bitmap的横向和纵向的像素值,如果裁剪的图像和这个像素值不符合,那么空白部分以黑色填充。

  intent.putExtra("noFaceDetection", true); // 是否去除面部检测, 如果你需要特定的比例去裁剪图片,那么这个一定要去掉,因为它会破坏掉特定的比例。

  intent.putExtra("return-data", true); //是否要返回值。 一般都要。

  startActivityForResult(intent, 1);

  //返回接受
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
      //数据有可能会没有反馈(图片清晰度太高或其他)
      if(data != null)
      {
        final Bitmap photo = data.getParcelableExtra("data");
        iv_lcon.setImageBitmap(photo);
      }else{
      }
    } else {
    // The contact that requested the photo is no longer present.
    // TODO: Show error message
    }
  }

5、EditText如何关闭软键盘

  方法一:
  在AndroidMainfest.xml中选择哪个activity,设置windowSoftInputMode属性为adjustUnspecified|stateHidden
  例如:<activity android:name=".Main"
      android:label="@string/app_name"
      android:windowSoftInputMode="adjustUnspecified|stateHidden"
      android:configChanges="orientation|keyboardHidden">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  方法二:
    强制隐藏Android输入法窗口
    例如:EditText edit=(EditText)findViewById(R.id.edit);
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(edit.getWindowToken(),0);

    2.EditText始终不弹出软件键盘
    例:EditText edit=(EditText)findViewById(R.id.edit);
    edit.setInputType(InputType.TYPE_NULL);

6、关于系统输入法

  1> 打开输入法窗口:

    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    // 接受软键盘输入的编辑文本或其它视图

    imm.showSoftInput(submitBt,InputMethodManager.SHOW_FORCED);

  2> 关闭出入法窗口  

    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    inputMethodManager.hideSoftInputFromWindow(OpeListActivity.this.getCurrentFocus().getWindowToken(),  

    InputMethodManager.HIDE_NOT_ALWAYS);  

    //接受软键盘输入的编辑文本或其它视图
    inputMethodManager.showSoftInput(submitBt,InputMethodManager.SHOW_FORCED);

  3> 如果输入法打开则关闭,如果没打开则打开

  InputMethodManager m=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

  m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

  4> 获取输入法打开的状态

  InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
  boolean isOpen=imm.isActive();
  isOpen若返回true,则表示输入法打开

  5> 自动弹出键盘(需要时间缓冲)
  Timer timer = new Timer();
  timer.schedule(new TimerTask(){
  public void run() {
    InputMethodManager m = (InputMethodManager)
    AccountEditer.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
  }}, 500);

  不让输入法影响布局的方法:

    1.修改AndroidManifest.xml文件,在Activity属性中加一条:
    android:windowSoftInputMode="adjustResize"

    2.在onCreate()——setContentView()函数后添加
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

7、跟时间有关的广播

  1> 时间被设置时发出的广播

    Intent.ACTION_TIME_CHANGED
  2>  当前时间已经变化(正常的时间流逝)。
    //当前时间改变,每分钟都发送,不能通过组件声明来接收,只有通过Context.registerReceiver()方法来注册
    Intent.ACTION_TIME_TICK

8、如何获取其他程序的Context

  Context othercontext = null;
  try {
    othercontext = createPackageContext("com.learn.android",
    Context.CONTEXT_IGNORE_SECURITY);
  } catch (NameNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

9、固定EditText光标的位置在最后

  Spannable spanText = (Spannable)et_data.getText();

  Selection.setSelection(spanText, et_data.getText().length());

  光标自动(在xml中添加)

  android:selectAllOnFocus="true"

10、在使用gallery控件时,左右滑动效果,与点击事件产生焦点冲突问题,导致滑动阻塞

    解决方法:监听gallery控件的OnTouch (setOnTouchListener)事件,在事件中处理。

    通过gallery.getSelectedItemPosition()获取当前的图片ID.

11、启动服务生命周期记录

  1> 采用Context.startService()方法启动服务有关的生命周期方法

    onCreate()->onStart() ->onDestroy()

    onCreate()该方法在服务被创建时调用,该方法只会被调用一次,无论调用多少次startService()或bindService()方法,服务也只被创建一次。

    onStart()只有采用Context.startService()方法启动服务时才会回调该方法。该方法在服务开始运行时被调用。多次调用startService()方法尽管不会多次创建服务,但  

        onStart() 方法会被多次调用。

    onDestroy()该方法在服务被终止时调用。

  2> 采用Context.bindService()方法启动服务有关的生命周期方法
    onCreate()->onBind() ->onUnbind->àonDestroy()

    onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()

        方法并不会导致该方法被多次调用。

    onUnbind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务解除绑定时被调用。

    如果先采用startService()方法启动服务,然后调用bindService()方法绑定到服务,再调用unbindService()方法解除绑定,最后调用bindService()方法再次绑定到服务,触发的

      生命周期方法如下:

    onCreate()->onStart()->onBind()->onUnbind()[调用bindService()方法再次绑定]->onRebind()
    //注意在onUnbind方法中
    public boolean onUnbind(Intent intent) {
      return true;//系统自动生成的super.onUnbind(intent)不行,必须返回true下次才可以绑定
    }

12、不需要焦点的跑马灯(TextView)

  public class MarqueeTextView extends TextView { 


  public MarqueeTextView(Context appCon) {
    super(appCon);
  }

  public MarqueeTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  public boolean isFocused() {
    return true;
  }

  @Override
  protected void onFocusChanged(boolean focused, int direction,
    Rect previouslyFocusedRect) {
    }
  }

  下面就是如何使用跑马灯的XML

  view plaincopyprint?<com.lta.mytransport.ui.utils.MarqueeTextView android:id="@+id/floodMsgView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:ellipsize="marquee"
    android:singleLine="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:freezesText="true"
    android:scrollHorizontally="true"
    android:text="@string/floodMsgDemo"
    android:marqueeRepeatLimit="marquee_forever"/>

13、截取指定号码的短信 并且不让系统获取短信通知用户

  使用 ContentObserver 来监听短信数据库变化

  Java 代码

  public class ScreenTest extends Activity {

    class SmsContent extends ContentObserver{

      private Cursor cursor = null;

      public SmsContent(Handler handler) {

        super(handler);

      }

      /**

      * @Description 当短信表发送改变时,调用该方法

      * 需要两种权限

      * Android.permission.READ_SMS 读取短信

      * android.permission.WRITE_SMS 写短信

      */

      @Override

      public void onChange(boolean selfChange) {

      // TODO Auto-generated method stub

      super.onChange(selfChange);

      //读取收件箱中指定号码的短信

      cursor = managedQuery(Uri.parse("content://sms/inbox"), new String[]{"_id", "address", "read"}, " address=? and read=?", new String[]{"12345678901", "0"}, "date desc");

      if (cursor != null){

        ContentValues values = new ContentValues();

        values.put("read", "1"); //修改短信为已读模式

        cursor.moveToFirst();

        while (cursor.isLast()){

        //更新当前未读短信状态为已读

        getContentResolver().update(Uri.parse("content://sms/inbox"), values, " _id=?", new String[]{""+cursor.getInt(0)});

        cursor.moveToNext();

      }

    }

  }

  }

  /** Called when the activity is first created. */

  @Override

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    SmsContent content = new SmsContent(new Handler());

    //注册短信变化监听

    this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"),true, content);

  }

}

14、使用最大内存

  在3.0以上
  在主配置文件中application中加入android:largeHeap="true"

15、java.math.Math类常用的常量和方法

  Math.PI 记录的圆周率

  Math.E记录e的常量
  Math.abs 求绝对值
  Math.sin 正弦函数 Math.asin 反正弦函数
  Math.cos 余弦函数 Math.acos 反余弦函数
  Math.tan 正切函数 Math.atan 反正切函数&nbsp;Math.atan2 商的反正切函数
  Math.toDegrees 弧度转化为角度 Math.toRadians 角度转化为弧度
  Math.ceil 得到不小于某数的最大整数
  Math.floor 得到不大于某数的最大整数

  例如:Math.floor(12.7) =12.0

  Math.ceil(12.7) =13.0

  ceil()是天花板,即向上取整。floor是地板,向下取整。round是四舍五入。

   Math.IEEEremainder 求余

  Math.max 求两数中最大
  Math.min 求两数中最小
  Math.sqrt 求开方
  Math.pow 求某数的任意次方, 抛出ArithmeticException处理溢出异常

  Math.sqrt(x):平方根
  Math.pow(x,y):x的y次方

  Math.exp 求e的任意次方
  Math.log10 以10为底的对数
  Math.log 自然对数
  Math.rint 求距离某数最近的整数(可能比某数大,也可能比它小)
  Math.round 同上,返回int型或者long型(上一个函数返回double型)
  Math.random 返回0,1之间的一个随机数

  java.math.BigInteger(大整数):
  BigInteger bi1=new BigInteger("1234567890123456890");
  BigInteger bi2=BigInteger.valueOf(123L);
  bi1=bi1.add(bi2);//b1+b2
  bi1=bi1.multiply(bi2);//b1*b2
  bi1=bi1.subtract(bi2);//b1-b2
  bi1=bi1.divide(bi2);// b1/b2

  java.math.BigDecimal(大浮点数):
  BigDecimal bd = new BigDecimal("3.1415926");
  bd = bd.setScale(2,BigDecimal.ROUND_DOWN);//取3.1415926小数点后面二位

16、设置系统亮度

  // 前提APK需要系统签名

  IPowerManager power = IPowerManager.Stub.asInterface(ServiceManager.getService("power"));
  try {
    if (power != null) {
    power.setBacklightBrightness(255);//20-255
    }
  } catch (RemoteException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
  <uses-permission android:name="android.permission.DEVICE_POWER"/>

17、Android控件样式自定义

  一、 控件常见状态:在XML文件中用到了selector节点,selector可以理解为状态切换器,
  不同的状态下切换不同的样式,各种状态用Item节点表示,以下为一些常见的状态
  (注意:statelist中第一个匹配当前状态的item会被使用。因此,如果第一个item没有任何状态特性的话,
  那么它将每次都被使用,这也是为什么默认的值必须总是在最后,各种状态可以交叉使用)

    1> android:state_pressed
    boolean “true”表示按下状态使用(例如按钮按下);“false”表示非按下状态使用。


    2> android:state_focused
    boolean “true”表示聚焦状态使用(例如使用滚动球/d-pad聚焦button);“false”表示非聚焦状态使用。


    3> android:state_selected
    boolean “true”表示选中状态使用(例如tab打开);“false”表示非选中状态使用。

    4> android:state_checkable    

    boolean “true”表示可勾选状态时使用;“false”表示非可勾选状态使用。(只对能切换可勾选—非可勾选的构件有用。) 

    5> android:state_checked

    boolean “true”表示勾选状态使用;“false”表示非勾选状态使用。

    6> android:state_enabled

    boolean  “true”表示可用状态使用(能接收触摸/点击事件);“false”表示不可用状态使用。

    7> android:window_focused

    boolean  “true”表示应用程序窗口有焦点时使用(应用程序在前台);“false”表示无焦点时使用(例如notification栏拉下或对话框显示)。 

  二、shape的属性:每个状态(item)都对应着一个效果,shape是用来定义形状的,以下为shape的一些常见属性:

    1、solid:实心,就是填充的意思
    android:color指定填充的颜色    

    2、gradient:渐变

    android:startColor和android:endColor分别为起始和结束颜色,android:angle是渐变角度,必须为45的整数倍。 当angle=0时,渐变色是从左向右。 然后逆时针方向转,当

    angle=90时为从下往上。 另外渐变默认的模式为android:type="linear",即线性渐变,可以指定渐变为径向渐变,android:type="radial",径向渐变需要指定半径

    android:gradientRadius="50",也可一指定二者的综合, 扫描渐变 android: type="sweep" 

    3、stroke:描边    

    android:width="2dp" 描边的宽度,android:color 描边的颜色。我们还可以把描边弄成虚线的形式,设置方式为:

    android:dashWidth="5dp"
    android:dashGap="3dp"
    其中android:dashWidth表示'-'这样一个横线的宽度,android:dashGap表示之间隔开的距离。


    4、corners:圆角
    android:radius为角的弧度,值越大角越圆。我们还可以把四个角设定成不同的角度,方法为:
    android:topRightRadius="20dp" 右上角
    android:bottomLeftRadius="20dp" 右下角
    android:topLeftRadius="1dp" 左上角
    android:bottomRightRadius="0dp" 左下角
    这里有个地方需要注意,bottomLeftRadius是右下角,而不是左下角

    5、panding:内边矩

    下面是一个Button完整的定义:
    java代码:
    <?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>

18、Android流量监控

    Android流量监控主要是有两种方法:

    一.抓包

      这个方法获取的流量更加精准,但是难度应该大点。

     二.读取linux本地文件

      Android是基于linux的一个操作系统。

      在Android中,你用Root Explorer去查看系统文件的话,与流量监控相关的会有这么几个文件

      /proc/net/dev这个文件中具体记录的暂时不是非常清楚,可能是整个系统的一个流量情况。

      /proc/uid_stat/%d" 和"/proc/uid_stat/%d" %d为进程的UID。这个文件里只有两项数据tcp_rcv和tcp_snd。

      看命名大家应该就能看出代表什么,一个代表总的接受字节数,一个代表总的发送字节数。

      这两个文件为非标准linux内核文件,由android内核层/kernel/net/Socket.c 的__sock_sendmsg函数负责写入, 用户层套接字通信在内核层最终会调用此函数 (包括本

      地套接字和网络套接字)。

      而Android在2.3之前是没有封装响应的流量监控API的。在2.3之后呢,把数据流量监控封装到了Android.net.TrafficStats类中。其原理就是读取上文提到的那几处文件。

      其中有的方法也是读取的别的文件。

      其主要的方法

        static long getMobileRxBytes()//获取通过Mobile连接收到的字节总数,但不包含WiFi
        static long getMobileRxPackets()//获取Mobile连接收到的数据包总数
        static long getMobileTxBytes()//Mobile发送的总字节数
        static long getMobileTxPackets()//Mobile发送的总数据包数
        static long getTotalRxBytes()//获取总的接受字节数,包含Mobile和WiFi等
        static long getTotalRxPackets()//总的接受数据包数,包含Mobile和WiFi等
        static long getTotalTxBytes()//总的发送字节数,包含Mobile和WiFi等
        static long getTotalTxPackets()//发送的总数据包数,包含Mobile和WiFi等
        static long getUidRxBytes(int uid)//获取某个网络UID的接受字节数
        static long getUidTxBytes(int uid) //获取某个网络UID的发送字节数

      返回类型均为long型,如果返回等于-1代表 UNSUPPORTED 当前设备不支持统计,可能是因为系统版本低。

      getUidRxBytes(int uid)此方法就是根据uid去查找系统中响应的文件,并读取响应的值。

      这其中可能遇到的问题是:没有wifi的情况下,各进程获得的getUidRxBytes之和与getMobileRxBytes所返回的值不相等。原因在于getUidRxBytes使读取上文提到的文

      件。而getMobileRxBytes读取的是sys/class/net/rmnet0/statistics/rx_bytes 和sys/class/net/ppp0/statistics/rx_bytes 。这俩文件。而且在getUidRxBytes返回的值中包含

      了本地通信的流量,比如本地进程间的socket通信。所以这两个值加起来有所出入!

 19、Android设置透明、半透明等效果

    设置透明效果 大概有三种

    1、用android系统的透明效果
    Java代码
      android:background="@android:color/transparent"

    例如 设置按钮
    Java代码
      <Button android:background="@android:color/transparent"

        android:text="@+id/Button01"

        android:id="@+id/Button01"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textColor="#ffffff" />

    2、用ARGB来控制
    Java代码
      半透明<Button android:background="#e0000000" />
      透明<Button android:background="#00000000" />

    3、设置alpha
    Java代码
      View v = findViewById(R.id.content);//找到你要设透明背景的layout 的id
      v.getBackground().setAlpha(100);//0~255透明度值





    android 窗体透明的,黑暗度等的设置技巧
    设置透明度(这是窗体本身的透明度,非背景)
    1 WindowManager.LayoutParams lp=getWindow().getAttributes();

    2 lp.alpha=0.3f;

    3 getWindow().setAttributes(lp);

    alpha在0.0f到1.0f之间。1.0完全不透明,0.0f完全透明


    设置黑暗度
      1 WindowManager.LayoutParams lp=getWindow().getAttributes();

      2 lp.dimAmount=0.5f;

      3 getWindow().setAttributes(lp);

      4 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        dimAmount在0.0f和1.0f之间,0.0f完全不暗,1.0f全暗


    设置背景模糊
      1 getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,

      2 WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

      以上设置对dialog对话框同样有效



    Activity的透明、半透明效果的设置transparent
    res/values/styles.xml

    <resources>
      <style name="Transparent">
        <item name="android:windowBackground">
          @color/transparent_background
        </item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">
          @+android:style/Animation.Translucent
        </item>
      </style>
    </resources>

    res/values/color.xml
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
      <color name="transparent_background">#50000000</color>
    </resources>
    //注意:
    //color.xml的#5000000前两位是透明的效果参数从00--99(透明--不怎么透明),
    //后6位是颜色的设置

    manifest.xml
    <activity
      android:name=".TransparentActivity"
      android:theme="@style/Transparent">
    </activity>

    java代码
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setTheme(R.style.Transparent);
      setContentView(R.layout.transparent);
    }

20、android应用程序界面不能铺满模拟器的整个屏幕

  新建一个模拟器 1024 X 768 的屏幕,自己建了应用程序一直不能暂满全屏,内容是完整的,只在屏幕的中间显示,像被缩小了似的。

  应用程序要指定SDK的最小版本,而且版本要不能小于8,即android2.2,在AndroidManifest.xml中增加一句即可:

  <uses-sdk android:minSdkVersion="8" />

21、TabHost分割线绘制

    //绘制控制选项卡指示符底部的分隔线
    tabHost.getTabWidget().setSaveEnabled(true);//是否可绘制
    tabHost.getTabWidget().setLeftStripDrawable(R.drawable.public_line_653);//左边可绘制的
    tabHost.getTabWidget().setRightStripDrawable(R.drawable.public_line_653);//右边可绘制的

22、获取各种储存信息(例如:内存大小、data大小)

    //获得系统可用内存信息 1
    ActivityManager mActivityManager =(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    String availMemStr = getSystemAvaialbeMemorySize();
    Log.d("", "内存大小:"+availMemStr);

    //获得系统可用内存信息 2
    private String getSystemAvaialbeMemorySize(){
      //获得MemoryInfo对象
      MemoryInfo memoryInfo = new MemoryInfo() ;
      //获得系统可用内存,保存在MemoryInfo对象上
      mActivityManager.getMemoryInfo(memoryInfo) ;
      long memSize = memoryInfo.availMem ;

      //字符类型转换
      String availMemStr = formateFileSize(memSize);

      return availMemStr ;
    }


    //SD卡存储大小
    void readSDCard() {
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state)) {
        File sdcardDir = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(sdcardDir.getPath());
        long blockSize = sf.getBlockSize();
        long blockCount = sf.getBlockCount();
        long availCount = sf.getAvailableBlocks();

        Log.d("" ,"路径名: "+ sdcardDir.getAbsolutePath() +" "+sdcardDir.getPath()+ "文件名:"+sdcardDir.getName()+ "block大小:" + blockSize+ ",block数目:" +

        blockCount+ ",总大小:" +formateFileSize(blockSize*blockCount) );
        Log.d("" , "可用的block数目::" + availCount+ ",剩余空间:" + formateFileSize(availCount*blockSize) );
      }
    }
    //系统目录存储大小
    void readSystem() {
      File root = Environment.getRootDirectory();
      StatFs sf = new StatFs(root.getPath());
      long blockSize = sf.getBlockSize();
      long blockCount = sf.getBlockCount();
      long availCount = sf.getAvailableBlocks();
      Log.d("", "路径名: "+ root.getAbsolutePath() +" "+root.getPath()+"文件名:"+root.getName()+ "内部 block大小:"+ blockSize+",内部 block数目:"+ blockCount+",内部 总

      大小:"+formateFileSize(blockSize*blockCount));
      Log.d("", "内部 可用的block数目::"+ availCount+",内部 可用大小:"+ formateFileSize(availCount*blockSize));
    }
    //Data目录存储大小
    void readData()
    {
      File data = Environment.getDataDirectory();
      StatFs sf = new StatFs(data.getPath());
      long blockSize = sf.getBlockSize();
      long blockCount = sf.getBlockCount();
      long availCount = sf.getAvailableBlocks();
      long a = sf.getFreeBlocks();
      Log.d("", "路径名: "+ data.getAbsolutePath() +" "+data.getPath()+"文件名:"+data.getName()+ "数据 block大小:"+ blockSize+",数据 block数目:"+ blockCount+",数据

      总大小:"+formateFileSize(blockSize*blockCount));
      Log.d("", "数据 可用的block数目::"+ availCount+",数据 可用大小:"+ formateFileSize(availCount*blockSize)+" "+ formateFileSize(a*blockSize));
    }

    //缓存目录存储大小
    void readCache()
    {
      File cache = Environment.getDownloadCacheDirectory();
      StatFs sf = new StatFs(cache.getPath());
      long blockSize = sf.getBlockSize();
      long blockCount = sf.getBlockCount();
      long availCount = sf.getAvailableBlocks();
      Log.d("", "路径名: "+ cache.getAbsolutePath() +" "+cache.getPath()+"文件名:"+cache.getName()+ "Cache block大小:"+ blockSize+",Cache block数目:"+

      blockCount+",Cache 总大小:"+formateFileSize(blockSize*blockCount));
      Log.d("", "Cache 可用的block数目::"+ availCount+",Cache 可用大小:"+ formateFileSize(availCount*blockSize));
    }

23、模拟菜单按钮

  IWindowManager windowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));

  try {
    windowManager.injectKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU), true);
    windowManager.injectKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU), true);
  } catch (RemoteException e) {
    e.printStackTrace();
  }

24、模拟键盘按键 

  //需要framework.jar
  final IWindowManager windowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
  try {
    windowManager.injectKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK), false);
  } catch (RemoteException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

25、判断是否是中文

  TextView v ;

  Character.isLetter(v.getText().charAt(i))

猜你喜欢

转载自www.cnblogs.com/gerall/p/11204284.html