让ListView实现跟QQ、微信、陌陌那样信息从底部开始 解决Android Studio Gradle Build Running 特别慢的问题

1、使用xmlPull解析xml数据得不到数据?但是解析方法是正确的


      首先检查自己的解析方法是否正确,如果没错的重点查找xml数据的“格式”是否正确!!


       比如上图,大家能看出传递过来的xml数据哪里不对。其实是这里<!--姓名 ->注释的格式不对,正确的应该是<!--姓名 -->,大家可以比较下看,后者比前者多了一个横线。如果数据格式是前者,即使解析方法正确,也得不到正确的值。

      虽然这种机会很少碰到,但是今天就遇到了,刚开始还以为自己的解析方法不对,查找了一个下午才找到。


      同时,如果解析的是字符串。可以用ByteArrayInputStream(str.getBytes)转为一个InputStream。



2、SVN提交错误:working copy is not up-to-date解决方法

svn在提交时报错如下图:

working copy is not up-to-date

svn:commit failed(details follow):

svn:file "xxxxx is out of date"

item is out of date

svn:item "xxxx" is out of date

解决方法:

在相应文件上,单击选择team,然后选择先更新,然后再提交。这样就好了


3、

android Spinner默认不选中项目开发中经常有些变态的需求,比如要求spinner默认不选中任何一项。

如果你自定义spinner,那这个当然不是问题;也可以在原有的选项列表中开头增加一项空字符串项,默认显示这个空字符串也达到了效果,不过采用这种方式需要你在获取被选择项的位置时忽略空字符串项。

经过一番摸索,发现我们只要保证 spinner第一次展示时不显示即可,相关代码如下:

boolean isSpinnerFirst = true ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main) ;
        Spinner spinner = (Spinner)findViewById(R.id.spinner) ;
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isSpinnerFirst) {
                    //第一次初始化spinner时,不显示默认被选择的第一项即可
                    view.setVisibility(View.INVISIBLE) ;
                }
                isSpinnerFirst = false ;
            }

            @Override
            public void onNothingSelected(AdapterView parent) {
            }
        }) ;
    }

4、安卓文本中一些特殊的文本输入,需要使用ASCII码

http://blog.csdn.net/z1074971432/article/details/12753539


5、文本颜色的字体选择器,注意不是用drawable了,而是使用color,(虽然drawable可以用颜色表示)

下面这个是字体颜色的选择器

[java]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.     <!-- index首页底部选择字体的 颜色选择器 -->  
  4.     <item android:state_selected="true"     android:color="@color/font_blue_color"></item>  
  5.     <item android:color="@color/font_black_color"></item>  
  6. </selector>  


下面这个是按钮的背景选择器

[java]  view plain  copy
  1. <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  2.       
  3.     <item android:drawable="@color/btn_rigth_pressed" android:state_pressed="true"></item>  
  4.     <item android:drawable="@color/btn_right_normal"></item>  
  5.   
  6. </selector>  


6、

今天无意中碰见了  case expressions must be constant expressions 的问题

 

写了一个

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. switch (v.getId()) {  
  2. case R.id.ivTitleBtnRightImage:  
  3.     LuTaiService xxService = mFragmentCallBack.getService();  
  4.     if (xxService == null || !xxService.isAuthenticated()) {  
  5.         return;  
  6.     }  
  7.     new AddRosterItemDialog(mFragmentCallBack.getMainActivity(),  
  8.             xxService).show();// 添加联系人  
  9.     break;  
  10.   
  11. default:  
  12.     break;  
  13. }  


导入到其它的工程里面  case R.id.ivTitleBtnRightImage :  出现了错误

错误提示为:case expressions must be constant expressions

网上查了一下  发现是 我的工程  勾选了isLibrary  的原因,将  勾选 去掉  再clear一下 就好




7、调用webService出现

Unexpected token (position:TEXT 
05-15 15:52:15.901: I/System. out (1429):  ------=_Part_0_...@5:13 in java.io.InputStreamReder

    正常情况下,android使用google的ksoap2这个包,就可以正常调用webService,前提条件是,服务端回传的必须是xml数据。

  出现这个异常,原因是服务端回传的不是xml数据,而是如下图所示


可以看到,回传的数据不是传统的xml数据,当ksoap2解析服务端数据,发现不是xml数据就报错了

这个时候,就不能用ksoa2去调用webService了,必须使用传统的http协议,发送post请求,代码如下


8、TabHost,添加TabWidget时,默认是有分割线的,可以在进行控制。

[html]  view plain  copy
  1. <TabWidget  
  2.                   android:id="@android:id/tabs"  
  3.                   android:layout_width="wrap_content"  
  4.                   android:layout_height="wrap_content"  
  5.                   android:showDividers="none"//这样tabwidget内tab间的分割线就没有了,就可以做viewpager的指示器了(内容是个imageview),显示到viewpager的哪一个item  
  6.                   android:divider="#ff00ff"   //这样tabwidget内tab间就又分割线了,而且分割线的颜色为#ff00ff  
  7.                   >  
  8.               </TabWidget>  

9、出现java.net.SocketException: socket failed: EACCES (Permission denied)

是没有添加权限,到主配置文件加上相应权限即可


10、fragmentTabHost之间 用bundle传值
 

[java]  view plain  copy
  1. // host.addTab(选项卡,内容,参数Bundle);  
  2.  host.addTab(tab, fragments[i], bundle);  

11、ViewUtil.inject()要放在setContenView()之下,否则出现空指针异常



12、一个float 保留2位小数,转成字符串

[java]  view plain  copy
  1. float result=(float) Math.random() * 30 + 15;  
  2. g.format("%.2f", result); //保留2为小数  

13、PullToRefresh

       在初始化完成PullToRefreshListView后,通过lv.getLoadingLayoutProxy()可得到一个ILoadingLayout对象,这个对象可设置各种指示器中的样式、文本等。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. ILoadingLayout startLabels = mPullRefreshListView    
  2.                 .getLoadingLayoutProxy();    
  3.         startLabels.setPullLabel("你可劲拉,拉...");// 刚下拉时,显示的提示    
  4.         startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新时    
  5.         startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下来达到一定距离时,显示的提示    
默认是上拉和下拉的字同时改变的,如果希望单独改变呢:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private void initIndicator(){    
  2.         ILoadingLayout startLabels = mPullRefreshListView    
  3.                 .getLoadingLayoutProxy(truefalse);    
  4.         startLabels.setPullLabel("你可劲拉,拉...");// 刚下拉时,显示的提示    
  5.         startLabels.setRefreshingLabel("好嘞,正在刷新...");// 刷新时    
  6.         startLabels.setReleaseLabel("你敢放,我就敢刷新...");// 下来达到一定距离时,显示的提示    
  7.     
  8.         ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(    
  9.                 falsetrue);    
  10.         endLabels.setPullLabel("你可劲拉,拉2...");// 刚下拉时,显示的提示    
  11.         endLabels.setRefreshingLabel("好嘞,正在刷新2...");// 刷新时    
  12.         endLabels.setReleaseLabel("你敢放,我就敢刷新2...");// 下来达到一定距离时,显示的提示  
参考 http://blog.csdn.net/mwj_88/article/details/39185921/

       http://blog.csdn.net/ueryueryuery/article/details/17440465

https://github.com/chrisbanes/Android-PullToRefresh/wiki/Quick-Start-Guide

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1215/2166.html


补充,这个控件有headView,所以索引是从1开始的,0为head

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    doSomething(parent.getAdapter().getItem(position));
}
在listView的setOnItemClickListener最后写上面的代码

或者   listData.get(position-1)

否则出现指针越界异常

参考

http://blog.chengbo.net/2012/03/09/onitemclick-return-wrong-position-when-listview-has-headerview.html

http://blog.csdn.net/sbvfhp/article/details/44959917



补充:如果这个pullToRefresh想增加setOnLongItemClick方法,请参考下面网址

http://blog.csdn.net/u012721519/article/details/51112560


注意:在PullToRefresh 源码里面并没有加入setOnItemLongClickerListener事件,如要使用该方法需自己添加该事件的使用方法,找到com.handmark.pulltorefresh.library 包下的PullToRefreshAdapterViewBase 类,添加以下代码即可。

[java]  view plain  copy
  1. public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener listener) {    
  2.         mRefreshableView.setOnItemLongClickListener(listener);    
  3.     }  




14、Android showDialog时报错requestFeature() must be called before adding content

01-08 10:06:54.670: E/AndroidRuntime(1968): android.util.AndroidRuntimeException: requestFeature() must be called before adding content
01-08 10:06:54.670: E/AndroidRuntime(1968): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:192)
01-08 10:06:54.670: E/AndroidRuntime(1968): at com.android.internal.app.AlertController.installContent(AlertController.java:234)
01-08 10:06:54.670: E/AndroidRuntime(1968): at android.app.AlertDialog.onCreate(AlertDialog.java:314)
01-08 10:06:54.670: E/AndroidRuntime(1968): at android.app.Dialog.dispatchOnCreate(Dialog.java:335)
01-08 10:06:54.670: E/AndroidRuntime(1968): at android.app.Dialog.show(Dialog.java:248)
01-08 10:06:54.670: E/AndroidRuntime(1968): at com.android.test.showDialog(MainActivity.java:121)

 

出现此问题是由于dialog.show()之前调用了dialog.setContentView()或者dialog.getwindow()等,正确的应该是dialog.show()之后调用dialog.setContentView()


参考

http://blog.csdn.net/lzt623459815/article/details/8479745



15、xutil的一些参考文档

http://www.tuicool.com/articles/MVNzUnI


Xutils3的使用


http://www.w2bc.com/Article/84851


xutil的多文件上传填写

[java]  view plain  copy
  1.                    HttpUtils http = new HttpUtils(10000);  
  2. RequestParams params = new RequestParams();  
  3. //设置文件  
  4. MultipartEntity entity = new MultipartEntity();  
  5. for (int i = 0; i < fileList.size();i++) {  
  6.     entity.addPart("file" + i,new FileBody(fileList.get(i)));     
  7. }  
  8. try {  
  9.     entity.addPart("creator"new StringBody(create_id_txt));  
  10.     entity.addPart("record_id"new StringBody(problem_id_txt));  
  11. catch (UnsupportedEncodingException e) {  
  12.     // TODO Auto-generated catch block  
  13.     e.printStackTrace();  
  14. }  




16、android给listview的item设定高度失败

http://blog.csdn.net/l_serein/article/details/7403992


四种方案解决ScrollView嵌套ListView问题


http://bbs.anzhuo.cn/thread-982250-1-1.html


17、

MultipartEntity与UrlEncodedFormEntity区别

http://www.pm-road.com/index.php/2014/10/16/118/


18 java去除字符中的HTML标记

http://shenyuc629.iteye.com/blog/1876378



19、常用的2个shape 和selector

下面这个是空心有边框的shape

[java]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android" >    
  3.     
  4.     <!-- 实心 -->    
  5.     <solid android:color="@android:color/white" />    
  6.       
  7.     <!-- 边框 -->    
  8.     <stroke    
  9.         android:width="0.5dp"    
  10.         android:color="#CBCBCB" />    
  11.           
  12.     <!-- 圆角 -->    
  13.     <corners android:radius="3dp" />    
  14.       
  15.     <!-- 边距 -->    
  16.     <padding    
  17.         android:bottom="1dp"    
  18.         android:left="6dp"    
  19.         android:right="6dp"    
  20.         android:top="1dp" />    
  21.           
  22. </shape>    



下面是一个正常情况透明,点击变色的selector

[java]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.       
  4.     <item android:state_pressed="true" >  
  5.          <shape>  
  6.              <solid android:color="@color/btn_green_predss" />   
  7.          </shape>  
  8.     </item>  
  9.       
  10.     <item android:state_enabled="false" >  
  11.          <shape>  
  12.              <solid android:color="@android:color/transparent" />   
  13.          </shape>  
  14.     </item>  
  15.       
  16.     <item>  
  17.          <shape>  
  18.              <solid android:color="@android:color/transparent" />   
  19.          </shape>  
  20.     </item>  
  21.       
  22. </selector>  

20、

[html]  view plain  copy
  1.     //GridView的常用布局  
  2.       <GridView  
  3.         android:id="@+id/gridView"  
  4.         android:layout_below="@id/actionbarLayout"  
  5.         android:layout_width="match_parent"  
  6.         android:layout_height="match_parent"  
  7.         android:numColumns="3"  
  8.         android:stretchMode="columnWidth"  
  9.         android:listSelector="@android:color/transparent"  
  10.         />  
  11.   
  12.   
  13.   
  14. //ListView的常用布局  
  15.            <ListView  
  16.            android:id="@+id/listview"  
  17.            android:layout_width="match_parent"  
  18.            android:layout_height="match_parent"   
  19.            android:layout_weight="1"  
  20.            android:background="@android:color/white"  
  21.            android:divider="#EBE7E8"  
  22.            android:dividerHeight="1dip"  
  23.            android:fadingEdge="none"  
  24.            android:fastScrollEnabled="false"  
  25.            android:footerDividersEnabled="false"  
  26.            android:headerDividersEnabled="false"  
  27.            android:smoothScrollbar="true"    />  

21、在oncreate()中利用view.getWidth()或是view.getHeiht()来获取view的宽和高,看似没有问题,其实他们去得值是0,并不是你想要的结果?

http://www.2cto.com/kf/201312/268110.html


[java]  view plain  copy
  1. View itemView=View.inflate(context, R.layout.item_hr_have_publish_position_detail, null);//这个是想要得到的layout布局  
  2.                                           
  3. int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);   
  4. int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);   
  5. itemView.measure(w, h);   
  6. int height =itemView.getMeasuredHeight();//这里得到了布局的高度  


//一个得到屏幕高度的工具类

[java]  view plain  copy
  1. ScreenUtil.initScreen(ReceiveResumeActivity.this);  
  2. int ScreenH=ScreenUtil.getScreenH();  

[java]  view plain  copy
  1. if(position==mResult.getTargetJobList().size()-1&&(position+1)*height>ScreenH){  
  2.      popWin.showAsDropDown(view, 0, -144);   //点击listView中的最后一个item,并且item的总长度大于屏幕高度,popupWindow显示上面  
  3.      }else{  
  4.      popWin.showAsDropDown(view, 00); //否则,popupWindow显示在item屏幕下方  
  5. }  


22、常用的技巧

一、标题栏的隐藏

方法1、

在Activity的oncreate方法中添加requestWindow()方法,需要注意的是它必须放在setsetContentView()方法之前,否则会报错。
[java]  view plain  copy
  1. public void onCreate(Bundle savedInstanceState) {  
  2.        super.onCreate(savedInstanceState);  
  3.        requestWindowFeature(Window.FEATURE_NO_TITLE);  
  4.        setContentView(R.layout.main);  
  5.        ……}  
方法2、
在配置文件Xml中设置Acitivity的theme属性
[java]  view plain  copy
  1. <activity  
  2.             android:theme="@android:style/Theme.NoTitleBar"       
  3.             android:name=".Test" >  
  4.             ……  
  5.  </activity>          

二、状态栏的隐藏

[java]  view plain  copy
  1.   public void onCreate(Bundle savedInstanceState) {  
  2.         super.onCreate(savedInstanceState);  
  3. //        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);    
  4.         setContentView(R.layout.main);  
  5.        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  
  6.        ……}  

在Activity的oncreate方法中添加requestWindow()方法,在setsetContentView()方法之前之后都可以。


三、全屏的实现
方法1、
在Activity的oncreate方法中设置
[java]  view plain  copy
  1. public void onCreate(Bundle savedInstanceState) {  
  2.        super.onCreate(savedInstanceState);  
  3.        this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  4.        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);   
  5.        setContentView(R.layout.main);  
  6.       ……}  
方法2、
在配置文件Xml中设置Acitivity的theme属性
[java]  view plain  copy
  1. <activity  
  2.             android:theme="@android:style/Theme.NoTitleBar.Fullscreen"       
  3.             android:name=".Test" >  
  4.             ……  
  5.  </activity>    
注意:
 以上三点只针对某一个Acitivity窗口进行设置,若想针对应用程序所有的Activity,那么直接在配置文件里进行设置,如
[java]  view plain  copy
  1. <application  
  2.    android:icon="@drawable/ic_launcher"  
  3.    android:label="@string/app_name"  
  4.     android:theme="@android:style/Theme.NoTitleBar.Fullscreen"   >  
那么所有Activity都会隐藏标题栏和状态栏,全屏显示。
 

23、unable to find attribute android:preserveIconSpacing 这个错误如何解决?

http://www.imooc.com/qadetail/89022

点击V7包找到values文件夹  ,打开attrs.xml   ,   ctrl+f   查找 MenuView  ,   将preserveIconSpacing注释掉或者删掉 , clean项目


24、Android PullToRefresh (ListView GridView 下拉刷新) 使用详解

http://blog.csdn.net/ljx19900116/article/details/41649195


25、Google自己的下拉刷新组件SwipeRefreshLayout

谷歌官方的swiperefreshlayout圆圈式下拉刷新,因为加了两个新的v4和v7兼容包,所以才有圆圈的效果,如果没有新的v4和v7兼容包,就是旧的彩线的效果.这里仅提供新的圆圈式效果。


如果想用圆圈的样式,需要去Android sdk manager里把Android support library升级到最新23版,如果是19版样式仍然是横线


26 SwipeMenuListView 需要引入一个外部库,代码

[java]  view plain  copy
  1. // step 1. 设置item 目录  
  2.     SwipeMenuCreator creator = new SwipeMenuCreator() {  
  3.   
  4.         @Override  
  5.         public void create(SwipeMenu menu) {  
  6.             //设置目录的选项  
  7.             SwipeMenuItem deleteItem = new SwipeMenuItem(context);  
  8.             // 设置目录背景 ,这里设置为红色  
  9.             deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,  
  10.                     0x3F0x25)));  
  11.             // 设置背景宽度  
  12.             deleteItem.setWidth(DensityUtil.dip2px(context, 90));  
  13.             // 设置背景图片  
  14.             deleteItem.setIcon(R.drawable.ic_delete);  
  15.             //添加都目录里  
  16.             menu.addMenuItem(deleteItem);  
  17.         }  
  18.     };  
  19.     //listView要添加目录  
  20.     lvPosition.setMenuCreator(creator);  
  21.       
  22.     // step 2. 设置目录监听器  
  23.     lvPosition.setOnMenuItemClickListener(new OnMenuItemClickListener() {  
  24.                 @Override  
  25.                 //目录的index ,表示目录item的数量,从0开始  
  26.                 //position  表示listView item的数量  
  27.                 public void onMenuItemClick(int position, SwipeMenu menu, int index) {  
  28.                     Position entity = positionList.get(position);  
  29.                     switch (index) {  
  30.                     case 0:  
  31.                         // 取消收藏  
  32.                           cancleCollect(entity.getPositionId());  
  33.                         positionList.remove(entity);  
  34.                         adapter.notifyDataSetChanged();  
  35.                         break;  
  36.                     }  
  37.                 }  
  38.             });  


27、点击查看大图代码 ,见youzi 的PositionDetailActivity

[java]  view plain  copy
  1. //点击查看大图  
  2. private  URL url=null;  
  3.    private  Bitmap bitmap = null;  
  4.    private  AlertDialog alertdialog ;  
  5. private ImageView imgView;  
  6.    private Handler handler=new Handler(){  
  7.       public void handleMessage(android.os.Message msg) {  
  8.           if(msg.what==1){  
  9.               imgView.setImageBitmap(bitmap);  
  10.               alertdialog.show();  
  11.               alertdialog.setContentView(imgView);  
  12.                   
  13.           }  
  14.       };  
  15.    };  
  16. //--点击查看大图分割线  




[java]  view plain  copy
  1. private void lookBigPic() {  
  2.         if (!TextUtils.isEmpty(detail.getLogo())) {  
  3.         //  CustomApplication.getBitmapUtils().display(ivLogo, URLConfig.SERVER_HOST_IMAGE + detail.getLogo());  
  4.       
  5.              alertdialog = new AlertDialog.Builder(context).create();  
  6.              imgView = new ImageView(context);  
  7.             imgView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,  
  8.                     LayoutParams.MATCH_PARENT));  
  9.               
  10.                 
  11.             new Thread(new Runnable() {  
  12.                 LoadingDialog dialog=  PromptUtil.showLoadingDialog(context,null);;  
  13.                 @Override  
  14.                 public void run() {  
  15.                       try {  
  16.                            
  17.                       
  18.                             url = new URL(URLConfig.SERVER_HOST_IMAGE  
  19.                                     + detail  
  20.                                     .getLogo());  
  21.                             InputStream is = url.openConnection().getInputStream();  
  22.                             BufferedInputStream bis = new BufferedInputStream(is);  
  23.                             bitmap = BitmapFactory.decodeStream(bis);  
  24.                             bis.close();  
  25.                              is.close();  
  26.                     } catch (MalformedURLException e) {  
  27.                             e.printStackTrace();  
  28.                     } catch (IOException e) {  
  29.                             e.printStackTrace();  
  30.                     }finally{  
  31.                         PromptUtil.closeLoadingDialog(dialog);  
  32.                         Message message=new Message();  
  33.                         message.what=1;  
  34.                         handler.sendMessage(message);  
  35.                          
  36.                     }  
  37.                       
  38.                 }  
  39.             }).start();  
  40.           
  41.         }  
  42.           
  43.     }  


28、

现在有一种需求,一个按钮的背景要显示3种颜色
1、enable模式
2  disables模式
3、点击press模式
4、不可press模式就是enable模式,默认都是为true


多用在短信验证码的按钮上

[java]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.       
  4.     <!-- 设置按压 -->  
  5.     <item android:state_pressed="true" >  
  6.          <shape>  
  7.              <solid android:color="@color/btn_rigth_pressed" />   
  8.          </shape>  
  9.     </item>  
  10.         
  11.       
  12.     <!-- 是否可以点击 -->  
  13.         <item android:state_enabled="true">  
  14.          <shape>  
  15.              <solid android:color="@color/btn_right_normal" />   
  16.          </shape>  
  17.     </item>  
  18.       
  19.              <item android:state_enabled="false">  
  20.          <shape>  
  21.              <solid android:color="#CDCDCD" />  这里是灰色颜色  
  22.          </shape>  
  23.     </item>  
  24.       
  25.       
  26. </selector>  


29、一个会犯错的布局,

如果一个Relative布局里面还有RelativeLayou,这个布局有点击事件,需要在里面的RelativeLayout布局里写clickable=true事件


[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:background="@android:color/white"  
  6.     android:orientation="horizontal">  
  7.   
  8.    <RelativeLayout   
  9.        android:layout_width="0dp"  
  10.        android:layout_weight="1"  
  11.        android:layout_height="wrap_content"  
  12.        android:layout_marginBottom="7dp"  
  13.        android:layout_marginTop="7dp"  
  14.        >  
  15.          
  16.         <TextView  
  17.             android:id="@+id/tv_name"  
  18.             android:layout_width="wrap_content"  
  19.             android:layout_height="wrap_content"  
  20.             android:layout_marginLeft="15dp"  
  21.             android:text="钱夫人"  
  22.             android:textColor="#000000"  
  23.             android:textSize="@dimen/main_text_size" />  
  24.   
  25.         <TextView  
  26.             android:id="@+id/tv_phone_number"  
  27.             android:layout_width="wrap_content"  
  28.             android:layout_height="wrap_content"  
  29.             android:layout_marginLeft="15dp"  
  30.             android:layout_toRightOf="@+id/tv_name"  
  31.             android:text="15989009065"  
  32.             android:textColor="#000000"  
  33.             android:textSize="@dimen/main_text_size" />  
  34.   
  35.         <TextView  
  36.             android:id="@+id/tv_address"  
  37.             android:layout_width="wrap_content"  
  38.             android:layout_height="wrap_content"  
  39.             android:layout_alignLeft="@+id/tv_name"  
  40.             android:layout_below="@+id/tv_name"  
  41.             android:layout_marginRight="8dp"  
  42.             android:layout_marginTop="10dp"  
  43.             android:ellipsize="end"  
  44.             android:maxLines="2"  
  45.             android:text="广州市天河区五山科华街"  
  46.             android:textColor="@color/font_gray_color"  
  47.             android:textSize="@dimen/sub_text_size" />  
  48.          
  49.    </RelativeLayout>  
  50.      
  51.   
  52.       <View  
  53.             android:id="@+id/view_line"  
  54.             android:layout_width="0.6dp"  
  55.             android:layout_height="match_parent"  
  56.             android:layout_marginBottom="6dp"  
  57.             android:layout_marginTop="6dp"  
  58.             android:background="@color/line_gray_color" />  
  59.       
  60.         <RelativeLayout  
  61.             android:id="@+id/rl_edit_address"  
  62.             android:layout_width="40dp"  
  63.             android:layout_height="match_parent"  
  64.             android:background="@drawable/selector_listview_item"  
  65.             android:clickable="true" >  
  66.   
  67.             <ImageView  
  68.                 android:id="@+id/iv_edit_address"  
  69.                 android:layout_width="20dp"  
  70.                 android:layout_height="20dp"  
  71.                 android:layout_centerInParent="true"  
  72.                 android:src="@drawable/icon_edit_address" />  
  73.         </RelativeLayout>  
  74.           
  75.    
  76.   
  77. </LinearLayout>  



30、压缩图片的2个笔记

1个是通过bitmap来压缩,适合通过startAcitivityForResult变形图片后,得到bitmap,上传到后台

1个是通过file来压缩,适合选择图片通过uri得到file上传到后台,要压缩来节省流量

http://www.360doc.com/content/14/0428/17/11800748_372972179.shtml
http://104zz.iteye.com/blog/1694762

[java]  view plain  copy
  1.         /** 
  2.   * 通过url得到图片文件 
  3.  * @param uri 
  4.  * @return 
  5.  * @author hemiy 
  6.  */  
  7.   
  8.   
  9. public File getFileByUri(Uri uri) {    
  10.         String path = null;    
  11.         if ("file".equals(uri.getScheme())) {    
  12.             path = uri.getEncodedPath();    
  13.             if (path != null) {    
  14.                 path = Uri.decode(path);    
  15.                 ContentResolver cr = context.getContentResolver();    
  16.                 StringBuffer buff = new StringBuffer();    
  17.                 buff.append("(").append(Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");    
  18.                 Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI, new String[] { Images.ImageColumns._ID, Images.ImageColumns.DATA }, buff.toString(), nullnull);    
  19.                 int index = 0;    
  20.                 int dataIdx = 0;    
  21.                 for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {    
  22.                     index = cur.getColumnIndex(Images.ImageColumns._ID);    
  23.                     index = cur.getInt(index);    
  24.                     dataIdx = cur.getColumnIndex(Images.ImageColumns.DATA);    
  25.                     path = cur.getString(dataIdx);    
  26.                 }    
  27.                 cur.close();    
  28.                 if (index == 0) {    
  29.                 } else {    
  30.                     Uri u = Uri.parse("content://media/external/images/media/" + index);    
  31.                     System.out.println("temp uri is :" + u);    
  32.                 }    
  33.             }    
  34.             if (path != null) {    
  35.                 return new File(path);    
  36.             }    
  37.         } else if ("content".equals(uri.getScheme())) {    
  38.             // 4.2.2以后    
  39.             String[] proj = { MediaStore.Images.Media.DATA };    
  40.             Cursor cursor = context.getContentResolver().query(uri, proj, nullnullnull);    
  41.             if (cursor.moveToFirst()) {    
  42.                 int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);    
  43.                 path = cursor.getString(columnIndex);    
  44.             }    
  45.             cursor.close();    
  46.     
  47.             return new File(path);    
  48.         } else {    
  49.             Log.i("d""Uri Scheme:" + uri.getScheme());    
  50.         }    
  51.         return null;    
  52.     }    

31、一些android的小知识点

判断服务是否启动

检测屏幕是否开启

获取进程名称

检测应用是否运行


http://www.tuicool.com/articles/juqIN3J




32、如何去掉ListView底部的ListDivider

http://blog.csdn.net/hustpzb/article/details/8072630

所以,如果ListView的高度是fill_parent,那么当Item很少,而没有能填满ListView的高度的时候,底部就会出现分割线。反之,如果ListView的高度是wrap_content,那么ListView的高度就是随着Item的增多而变高的,最后一行的Item始终是达到了ListView的底部,也就不会出现分割线了。


33、 

让ListView实现跟QQ、微信、陌陌那样信息从底部开始

http://blog.csdn.net/minglun1234/article/details/22086875

让自己的聊天界面ListView实现向众多聊天软件那样从底部开始,其实很简单,只需要在实例化的ListView设置setStackFromBottom(true);即可实现刚刚开始的信息是显示在底部的~~


34、一个关于邮箱的正则表达式

/^[a-zA-Z0-9#_~!$&'()*+,;=:."(),:;<>@\[\]\\]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/


35、删除文件夹里面所有文件的代码

private void deleteAllFileDir(File file) {
if (file.exists()) {//判断文件是否存在  
    if (file.isFile()) {//判断是否是文件  
     file.delete();//删除文件   
    } else if (file.isDirectory()) {//否则如果它是一个目录  
     File[] files = file.listFiles();//声明目录下所有的文件 files[];  
     for (int i = 0;i < files.length;i ++) {//遍历目录下所有的文件  
      this.deleteAllFileDir(files[i]);//把每个文件用这个方法进行迭代  
     }  
     file.delete();//删除文件夹  
    }  
   } else {  
    System.out.println("所删除的文件不存在");  
  //  return;
   } 

}


36、 android控件EditText的setOnEditorActionListener方法理解


当我们定义一个可编辑控件EditText时

EditText ET_phone = (EditText) findViewById(R.id.ET_phonenumber);

会添加一个方法:

[java]  view plain  copy
  1. ET_phone.setOnEditorActionListener(new OnEditorActionListener() {    
  2.       @Override    
  3.       public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {    
  4.           Log.e("点击ET_phone""没有响应");    
  5.           text.setText("Editing ET_phonenumber");    
  6.           return false;    
  7.       }    
  8.   });   
需要注意的是 setOnEditorActionListener这个方法, 并不是在我们点击EditText的时候触发,也不是在我们对EditText进行编辑时触发,而是在我们编辑完之后点击软键盘上的回车键才会触发。 

37、listView中图片加载出现错位的一个解决方案

首先,图片加载错位可以参考文章

http://blog.csdn.net/guolin_blog/article/details/45586553


核心思路是,给图片控件添加一个tag,这个tag是图片的网络地址,当获取的网络图片地址和tag不一样时,才添加新的网络图片

[java]  view plain  copy
  1. String profilePhoto=entity.getProfilePhoto();  
  2. if(!TextUtils.isEmpty(profilePhoto)){  
  3.     if(!profilePhoto.equals(holder.ivAvatar.getTag())){  
  4.         CustomApplication.getBitmapUtils().display(holder.ivAvatar, URLConfig.SERVER_HOST+profilePhoto,DefaultHeader.getDefaultHeader());  
  5.         holder.ivAvatar.setTag(profilePhoto);//当出现不一致时,才设置新的图片  
  6.     }  
  7. }else{  
  8.     holder.ivAvatar.setImageResource(R.drawable.avatar);  //没有网络图片,设置为默认的本地图片  
  9.     holder.ivAvatar.setTag(null);  
  10. }  


38、gridView的一些总结

[html]  view plain  copy
  1. <!--这里只用设置列数即可,其他的参数可以不要-->  
  2. GridView  
  3. android:id="@+id/gridView"  
  4. android:gravity="center"  
  5. android:layout_width="match_parent"  
  6. android:layout_height="match_parent"  
  7. android:numColumns="4"  
  8. android:horizontalSpacing="5dp"  
  9. android:verticalSpacing="5dp">  

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:gravity="center"  
  5.     android:padding="10dp"  
  6.     android:layout_width="wrap_content"  
  7.     android:layout_height="wrap_content">  
  8.   
  9.     <!--item的宽度可以设置为任意长度,但是高度可以自定义。-->  
  10.     <!--比如图片的宽随便取值,但是高度会具体反映在gridView上-->  
  11.   
  12.     <ImageView  
  13.         android:src="@drawable/icon_female_pressed"  
  14.         android:id="@+id/image"  
  15.         android:layout_width="600dp"  
  16.         android:layout_height="50dp"  
  17.         />  
  18.   
  19.     <TextView  
  20.         android:id="@+id/text"  
  21.         android:layout_marginTop="5dp"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:textColor="@color/black"  
  25.         android:text="文字"  
  26.         />  
  27. </LinearLayout>  


39、改变toast的字体大小

[java]  view plain  copy
  1. Toast toast = Toast.makeText(IndexActivity.this"这个是一个测试", Toast.LENGTH_SHORT);  
  2. // 修改Toast字体大小  
  3. LinearLayout linearLayout = (LinearLayout) toast.getView();  
  4. TextView messageTextView = (TextView) linearLayout.getChildAt(0);  
  5. messageTextView.setTextSize(25);  
  6. // 显示Toast  
  7. toast.show();  

40、垂直的seekbar

http://blog.csdn.net/liangguo03/article/details/7048793 

http://blog.csdn.net/dreambegin/article/details/7196167  可以用这个,效果好



41、spinner控件详解

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0105/2264.html


42、递归遍历文件夹下的所有文件

[java]  view plain  copy
  1. public static List<File> getFileList(String strPath) {  
  2.        File dir = new File(strPath);  
  3.        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组  
  4.        if (files != null) {  
  5.            for (int i = 0; i < files.length; i++) {  
  6.                String fileName = files[i].getName();  
  7.                if (files[i].isDirectory()) { // 判断是文件还是文件夹  
  8.                    getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径  
  9.                } else if (fileName.endsWith("avi")) { // 判断文件名是否以.avi结尾  
  10.                    String strFileName = files[i].getAbsolutePath();  
  11.                    System.out.println("---" + strFileName);  
  12.                    filelist.add(files[i]);  
  13.                } else {  
  14.                    continue;  
  15.                }  
  16.            }  
  17.   
  18.        }  
  19.        return filelist;  
  20.    }  

补充阅读:

FilenameFilter的使用

http://www.cnblogs.com/azhqiang/p/4596783.html



43、最近在用android studio 用了一个gitup上的下拉刷新库,样式是挺美观的

https://github.com/android-cjj/Android-MaterialRefreshLayout

主要功能是在viewPager里放了4个fragment,滑动时切换4个页面,每个页面都有下拉刷新功能,出现一个问题,当加入以下代码容易出现报错(前2个fragment正常,第34个fragment就报错)

[java]  view plain  copy
  1. //切换页面  
  2.  viewPager.setCurrentItem(type);  
报错信息如下
[java]  view plain  copy
  1. java.lang.NullPointerException  
  2. at com.cjj.MaterialRefreshLayout.setProgressValue(MaterialRefreshLayout.java:393)  
  3. at com.cjj.MaterialRefreshLayout.finishRefreshing(MaterialRefreshLayout.java:484)  
  4. at com.cjj.MaterialRefreshLayout$2.run(MaterialRefreshLayout.java:492)  
  5. at android.os.Handler.handleCallback(Handler.java:733)  
  6. at android.os.Handler.dispatchMessage(Handler.java:95)  
  7. at android.os.Looper.loop(Looper.java:136)  
  8. at android.app.ActivityThread.main(ActivityThread.java:5072)  
  9. at java.lang.reflect.Method.invokeNative(Native Method)  
  10. at java.lang.reflect.Method.invoke(Method.java:515)  
  11. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)  
  12. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)  
  13. at dalvik.system.NativeStart.main(Native Method)  

上网搜索了下一,发现出现同样的问题同学也不少

https://github.com/android-cjj/Android-MaterialRefreshLayout/issues/35

解决办法 先用google官方的swipeRefreshLayout代替先 ,这里记录下


44、webview使用的一些总结

http://www.cnblogs.com/tony-yang-flutter/p/3565023.html

(1)不跳转到系统的浏览器,直接在当前webview中打开当前地址(其实只要setWebviewClient(new WebviewClient()也行,不用重新里面的方法)

[java]  view plain  copy
  1.       webview.setWebViewClient(new WebViewClient() {  
  2.     @Override  
  3.     public boolean shouldOverrideUrlLoading(WebView view, String url) {  
  4.     view.loadUrl(url)  
  5.     return true;//这里如果用view.stopLoading()可以不执行url的加载,相当于拦截了当前的url请求  
  6.     }  
  7. });  

(2)允许弹出js窗口

[java]  view plain  copy
  1.               webSettings.setJavaScriptEnabled(true); // 设置WebView属性,能够执行Javascript脚本  
  2.   
  3. webSettings.setJavaScriptCanOpenWindowsAutomatically(true);// 可以弹出js弹窗  
  4.   
  5. webview.setWebChromeClient(new WebChromeClient()); // 在加载网页前加上这句就可以了,用于加载js他弹出窗口  

(3) 

[java]  view plain  copy
  1. //如果不做任何处理,浏览网页,点击系统“Back”键,整个Browser会调用finish()而结束自身  
  2.  //,如果希望浏览的网 页回退而不是推出浏览器,需要在当前Activity中处理并消费掉该Back事件。  
  3.  public boolean onKeyDown(int keyCode, KeyEvent event) {         
  4.          if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {         
  5.              webView.goBack();//退回到上一个页面         
  6.              return true;         
  7.          }         
  8.          return super.onKeyDown(keyCode, event);         
  9.   }    

(4)

[java]  view plain  copy
  1. //显示进度  
  2.     webView.setWebChromeClient(new WebChromeClient(){  
  3.         @Override  
  4.         public void onProgressChanged(WebView view, int newProgress) {  
  5.             Log.e("newProgress", newProgress+"");  
  6.             progressBar.setProgress(newProgress);  
  7.             if(newProgress >= 100){  
  8.                 progressBar.setVisibility(View.GONE);  
  9.             }  
  10.               super.onProgressChanged(view, newProgress);  
  11.         }  
  12.           
  13.     });  

点击打开链接

45、AlertDialog是系统自带的一个常用的dialog,非常常用

(1)使用系统自带的

[java]  view plain  copy
  1.       new AlertDialog.Builder(getActivity())  
  2.  .setTitle("标题文字")  
  3. .setItems(“自己的数组”, new DialogInterface.OnClickListener() {  
  4.         /**当点击对话框的列表项时,回调该方法 
  5.          * dialog:AlertDialog 
  6.          * which:你点了哪一个列表项 
  7.          */  
  8.     @Override  
  9.     public void onClick(DialogInterface dialog, int which) {  
  10.                               
  11.         }  
  12.     })  
  13.      .create()  
  14.      .show();  


(2)dialog的内容可以自己定义

[java]  view plain  copy
  1.       AlertDialog dialog1 = new AlertDialog.Builder(getActivity()).create();  
  2.         ImageView imgView=null;  
  3.         try {  
  4.             imgView = creatNewView()//创建一个新的图片  
  5.         } catch (FileNotFoundException e) {  
  6.             e.printStackTrace();  
  7.         }  
  8. dialog1.show(); //注意这里的顺序不能乱  
  9. dialog1.setContentView(imgView);  

(3)

http://blog.csdn.net/bitian123/article/details/51982038

设置dialog宽度为屏幕宽度:

        Window window = dialog.getWindow();

        window.setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.anim_push_out);  //添加动画
        dialog.show(); //注意,参数的设置必须放在show方法后面,否则会报错
        //设置dialog的宽度和手机宽度一样
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = window.getWindowManager().getDefaultDisplay().getWidth();

        dialog.getWindow().setAttributes(lp);//设置宽度


但是往往dialog还是会有margin,

这时可以给这个AlertDialog设置自定义的样式:

AlertDialog dialog = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.MyAlertDialog))
                .setView(view)
                .create();


在样式中把margin设为为负数:

<style name="MyAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="Android:layout_marginLeft">-10dp</item>
        <item name="android:layout_marginRight">-10dp</item>
        <item name="android:layout_marginBottom">-5dp</item>
    </style>


这样这个AlertDialog就是宽度为屏幕宽度,并且和底部没有margin的了。


(4)rd项目中,dialog的设置为全屏自己的代码参考

[java]  view plain  copy
  1.               note_dlg = new NoteDialog(context, BookShower.this, subType);  
  2. note_dlg.show();  
  3.   
  4. //以下代码必须放在dialog.show()方法后,否则会报错  
  5. //设置dialog全屏  
  6. //"http://bbs.csdn.net/topics/390175091"  
  7. Window win = note_dlg.getWindow();  
  8. win.getDecorView().setPadding(0000);//默认还是有padding 所以还要这么设置  
  9. WindowManager.LayoutParams lp = win.getAttributes();  
  10. lp.width = WindowManager.LayoutParams.MATCH_PARENT;  
  11.     lp.height = WindowManager.LayoutParams.WRAP_CONTENT;  
  12. win.setAttributes(lp);  

46、    

解决Android Studio Gradle Build Running 特别慢的问题



第一步:
\Users\你的用户名\.gradle目录下新建一个文件名为gradle.properties的文件。
内容为:
org.gradle.daemon=true

第二步:
到 Android Studio 安装目录,找到bin/studio(64?).vmoptions(文件名可能因操作系统而不同,但大同小异),然后把 -xmx 后面的数字改大一点。
以自己的为例

-Xms2048m
-Xmx2048m
-XX:MaxPermSize=2048m
-XX:ReservedCodeCacheSize=1024m

47、自定义view时,比如new一个出来,则它的参数也需要new一个出来




48、如果修改系统自带的toast字体大小
[java]  view plain  copy
  1. Toast to=Toast.makeText(MemoActivity.this"保存成功"1);  
  2. LinearLayout linearLayout = (LinearLayout) to.getView();    
  3. extView messageTextView = (TextView) linearLayout.getChildAt(0);    
  4. messageTextView.setTextSize(23f);    
  5. to.show();  


49、
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

出现这个问题,注意检查下,子线程不能做ui操作


50、做项目出现一个问题,有一个水平方向的ListView,想把里面的item的宽度根据屏幕大小平均分配,使用如下的代码去设置宽度总是失败,导致总是无法平均分配宽度

 convertView.setLayoutParams(params);


上网后找到了原因:因为adapter里面的item的布局是LinearLayout,把它改为RelativeLayout即可

参考网址 :http://www.imooc.com/qadetail/83537

正确的代码如下



51、使用context启动Activity要注意的问题




52、使用谷歌官方的drawerLayout,当弹出侧滑菜单会把主界面遮盖,如果想主界面也一同移动使用下面的代码

[java]  view plain  copy
  1. https://segmentfault.com/q/1010000006682881  主界面不要被覆盖 参考网址  

[java]  view plain  copy
  1.   drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {  
  2.             @Override  
  3.             public void onDrawerSlide(View drawerView, float slideOffset) {           
  4.                 linearLayout.setTranslationX(slideOffset * drawerView.getWidth());  
  5.   
  6. //                http://blog.csdn.net/adfsadsfa/article/details/43481929   取消主界面透明度变化 先不要  
  7. //                drawerLayout.setScrimColor(0x00ffffff);  
  8.             }  

53、版本4.4-5.1界面侵入状态栏,想给状态栏设置颜色

[java]  view plain  copy
  1. //下面的是当4.4版本,contentView会侵入状态栏,所以设置了一个padding,并给状态栏设置颜色  
  2.        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT <=21)  
  3.        {  
  4.            //因为整个界面侵入了状态栏,所以把整体布局往下拉,注意这里布局移动是linearLayout,而不是contentView  
  5.            int resourceId = getResources().getIdentifier("status_bar_height""dimen""android");  
  6.            int statusBarHeight = getResources().getDimensionPixelSize(resourceId);  
  7.            linearLayout.setPadding(0, statusBarHeight, 00);//linearLayout就是主界面的布局  
  8.            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//使 ContentView 内容覆盖状态栏  
  9.   
  10.   
  11.            //下面5句是设置状态栏的颜色,只适用于4.4-5.1版本之间的修改  
  12.            ViewGroup contentView = (ViewGroup) this.findViewById(android.R.id.content);  
  13.            View statusBarView = new View(this);  
  14.            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,  
  15.                    getStatusBarHeight(this));  
  16.            statusBarView.setBackgroundColor(Color.parseColor("#66CCFF"));  
  17.            contentView.addView(statusBarView, lp);  
  18.        }  

54、版本5.1以上设置状态栏颜色

[java]  view plain  copy
  1. public void smoothSwitchScreen() {  
  2.   
  3.         if (Build.VERSION.SDK_INT >=22) {  
  4.             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//使 ContentView 内容不再覆盖状态栏  
  5.             //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色  
  6.             getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
  7.             getWindow().setStatusBarColor(Color.parseColor("#66CCFF")); //当使用这个方法,activity里面的主题也不要使用darkPrimaryColor属性了  
  8.   
  9.         }  


55、全屏activity切换到非全屏activity时候,出现黑边和卡顿问题,参考下面的网址

http://blog.csdn.net/u013011318/article/details/48296869 

 
   
 
   

56、把旧文件拷贝到新文件的方法

[java]  view plain  copy
  1. /** 
  2.      * 拷贝目标文件到新的文件下 
  3.      *  
  4.      * @param oldFile 
  5.      * @param newFile 
  6.      */  
  7.     private static void copyFile(File oldFile, File newFile) {  
  8.         FileOutputStream outputStream = null;  
  9.         FileInputStream inputStream = null;  
  10.         try {  
  11.             outputStream = new FileOutputStream(newFile, true);  
  12.             inputStream = new FileInputStream(oldFile);  
  13.             byte[] byt = new byte[1024];  
  14.             int length = inputStream.read(byt);  
  15.             while (length != -1) {  
  16.                 outputStream.write(byt, 0, length);  
  17.                 length = inputStream.read(byt);  
  18.             }  
  19.         } catch (Exception e) {  
  20.             e.printStackTrace();  
  21.         } finally {  
  22.             if (outputStream != null) {  
  23.                 try {  
  24.                     outputStream.close();  
  25.                 } catch (IOException e) {  
  26.                 }  
  27.             }  
  28.             if (inputStream != null) {  
  29.                 try {  
  30.                     inputStream.close();  
  31.                 } catch (IOException e) {  
  32.                 }  
  33.             }  
  34.         }  
  35.     }  


57、一个类似word搜索的,搜索关键字黄色高亮的代码,核心代码是用到了

SpannableStringBuilder


参考网址:http://www.jianshu.com/p/f004300c6920

逻辑思路是在BaseAdapter里面的getView方法里,根据关键词的索引

[java]  view plain  copy
  1. int index=meetVO.meetingName.indexOf(key);//查找文字在字符串里面第一次出现的索引值  
  2. SpannableStringBuilder spannableString = new SpannableStringBuilder();  
  3. spannableString.append(meetVO.meetingName);  
  4. BackgroundColorSpan bgColorSpan = new BackgroundColorSpan(Color.parseColor("#FFE03D"));//设置背景色为黄色  
  5. spannableString.setSpan(bgColorSpan, index,index+key.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); //这里的key就是关键词  
  6. holder.mTitle.setText(spannableString);//这里的关键字要加黄色背景色  


58、一个手机号码格式的正则表达式

http://www.jianshu.com/p/b1d8c6928bad

直接使用下面的字符串即可

(?:(?:(?:13[0-9])|(?:14[57])|(?:15[0-35-9])|(?:17[36-8])|(?:18[0-9]))\d{8})|(?:170[057-9]\d{7})

59、 Android 6.0 ProgressBar 自定义动画不显示问题
最近在做项目的时候,要显示一个类似ios的loadingDialog,其他版本显示正常,但是6.0就没有那个旋转的图片,在网上找了下

http://blog.csdn.net/dongbeitcy/article/details/52768074

[java]  view plain  copy
  1. public class LoadingDialogIos extends Dialog {  
  2.   
  3.     private TextView tips_loading_msg;  
  4.     private String message ;  
  5.     private Context context;  
  6.   
  7.     /** 
  8.      * 构造方法 
  9.      * 
  10.      * @param context 
  11.      *            上下文 
  12.      * @param layoutResId 
  13.      *            要传入的dialog布局文件的id 
  14.      */  
  15.     public LoadingDialogIos(Context context,String msg) {  
  16.         super(context, R.style.loadingDialogStyle);//这个样式必须要有,否则出现黑色边框外面还有白色背景框的情况  
  17.         this.message = msg;  
  18.         this.context=context;  
  19.     }  
  20.   
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         this.setContentView( R.layout.view_tips_loading2);  
  25.           
  26.               
  27.         if (android.os.Build.VERSION.SDK_INT > 22) {//android 6.0替换clip的加载动画  
  28.              Drawable drawable = context.getApplicationContext().getResources().getDrawable(R.drawable.loading_for_android6);  
  29.              ProgressBar pBar=(ProgressBar) findViewById(R.id.pBar);  
  30.              pBar.setIndeterminateDrawable(drawable);  
  31.         }  
  32.   
  33.         //输入提示文本框的文字  
  34.         tips_loading_msg = (TextView) findViewById(R.id.tips_loading_msg);  
  35.        if(!TextUtils.isEmpty(message)){  
  36.            tips_loading_msg.setVisibility(View.VISIBLE);  
  37.            tips_loading_msg.setText(message);  
  38.        }  
  39.     }  
  40.   
  41. }  

[java]  view plain  copy
  1. <!-- 加载框样式 -->  
  2.    <style name="loadingDialogStyle" parent="android:Theme.Dialog">  
  3.        <item name="android:windowBackground">@android:color/transparent</item>  
  4.        <item name="android:windowFrame">@null</item>  
  5.        <item name="android:windowNoTitle">true</item>  
  6.        <item name="android:windowIsFloating">true</item>  
  7.        <item name="android:windowIsTranslucent">true</item>  
  8.        <item name="android:windowContentOverlay">@null</item>  
  9.    </style>  

loadingDialog的布局

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="wrap_content"  
  4.     android:layout_height="wrap_content"  
  5.     android:layout_gravity="center"  
  6.     android:background="@drawable/tips_bg"  
  7.     android:gravity="center" >  
  8.     <View  
  9.         android:layout_width="80dip"  
  10.         android:layout_height="80dip"  
  11.         android:layout_centerInParent="true" />  
  12.     <LinearLayout  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_centerInParent="true"  
  16.         android:orientation="vertical" >  
  17.         <ProgressBar  
  18.             android:id="@+id/pBar"  
  19.             android:layout_width="50dp"  
  20.             android:layout_height="50dp"  
  21.             android:layout_gravity="center"  
  22.             android:layout_marginBottom="1dp"  
  23.             android:clickable="false"  
  24.             android:gravity="center"  
  25.             android:indeterminateDrawable="@drawable/loading" />  
  26.         <TextView  
  27.             android:id="@+id/tips_loading_msg"  
  28.             android:layout_width="wrap_content"  
  29.             android:layout_height="wrap_content"  
  30.             android:layout_gravity="center"  
  31.             android:gravity="center"  
  32.             android:lineSpacingExtra="3.0dip"  
  33.             android:visibility="gone"  
  34.             android:layout_marginTop="7dp"  
  35.             android:textColor="#ffffffff"  
  36.             android:textSize="15sp" />  
  37.     </LinearLayout>  
  38. </RelativeLayout>  


[java]  view plain  copy
  1. @drawable/loading的代码  
[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <animation-list xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:oneshot="false" >  
  4.   
  5.     <item android:duration="150">  
  6.         <clip  
  7.             android:clipOrientation="horizontal"  
  8.             android:drawable="@drawable/ic_loading_white_01"  
  9.             android:gravity="left" />  
  10.     </item>  
  11.     <item android:duration="150">  
  12.         <clip  
  13.             android:clipOrientation="horizontal"  
  14.             android:drawable="@drawable/ic_loading_white_02"  
  15.             android:gravity="left" />  
  16.     </item>  
  17.     <item android:duration="150">  
  18.         <clip  
  19.             android:clipOrientation="horizontal"  
  20.             android:drawable="@drawable/ic_loading_white_03"  
  21.             android:gravity="left" />  
  22.     </item>  
  23.     <item android:duration="150">  
  24.         <clip  
  25.             android:clipOrientation="horizontal"  
  26.             android:drawable="@drawable/ic_loading_white_04"  
  27.             android:gravity="left" />  
  28.     </item>  
  29.     <item android:duration="150">  
  30.         <clip  
  31.             android:clipOrientation="horizontal"  
  32.             android:drawable="@drawable/ic_loading_white_05"  
  33.             android:gravity="left" />  
  34.     </item>  
  35.     <item android:duration="150">  
  36.         <clip  
  37.             android:clipOrientation="horizontal"  
  38.             android:drawable="@drawable/ic_loading_white_06"  
  39.             android:gravity="left" />  
  40.     </item>  
  41.     <item android:duration="150">  
  42.         <clip  
  43.             android:clipOrientation="horizontal"  
  44.             android:drawable="@drawable/ic_loading_white_07"  
  45.             android:gravity="left" />  
  46.     </item>  
  47.     <item android:duration="150">  
  48.         <clip  
  49.             android:clipOrientation="horizontal"  
  50.             android:drawable="@drawable/ic_loading_white_08"  
  51.             android:gravity="left" />  
  52.     </item>  
  53.     <item android:duration="150">  
  54.         <clip  
  55.             android:clipOrientation="horizontal"  
  56.             android:drawable="@drawable/ic_loading_white_09"  
  57.             android:gravity="left" />  
  58.     </item>  
  59.     <item android:duration="150">  
  60.         <clip  
  61.             android:clipOrientation="horizontal"  
  62.             android:drawable="@drawable/ic_loading_white_10"  
  63.             android:gravity="left" />  
  64.     </item>  
  65.     <item android:duration="150">  
  66.         <clip  
  67.             android:clipOrientation="horizontal"  
  68.             android:drawable="@drawable/ic_loading_white_11"  
  69.             android:gravity="left" />  
  70.     </item>  
  71.     <item android:duration="150">  
  72.         <clip  
  73.             android:clipOrientation="horizontal"  
  74.             android:drawable="@drawable/ic_loading_white_12"  
  75.             android:gravity="left" />  
  76.     </item>  
  77.   
  78. </animation-list>  

[java]  view plain  copy
  1. loading_for_android6的代码  
[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <animation-list xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:oneshot="false"  
  4.     android:variablePadding="true" >  
  5.   
  6.     <item  
  7.         android:drawable="@drawable/ic_loading_white_01"  
  8.         android:duration="100"  
  9.         android:gravity="center">  
  10.     </item>  
  11.     <item  
  12.         android:drawable="@drawable/ic_loading_white_02"  
  13.         android:duration="100"  
  14.         android:gravity="center">  
  15.     </item>  
  16.     <item  
  17.         android:drawable="@drawable/ic_loading_white_03"  
  18.         android:duration="100"  
  19.         android:gravity="center">  
  20.     </item>  
  21.     <item  
  22.         android:drawable="@drawable/ic_loading_white_04"  
  23.         android:duration="100"  
  24.         android:gravity="center">  
  25.     </item>  
  26.     <item  
  27.         android:drawable="@drawable/ic_loading_white_05"  
  28.         android:duration="100"  
  29.         android:gravity="center">  
  30.     </item>  
  31.     <item  
  32.         android:drawable="@drawable/ic_loading_white_06"  
  33.         android:duration="100"  
  34.         android:gravity="center">  
  35.     </item>  
  36.     <item  
  37.         android:drawable="@drawable/ic_loading_white_07"  
  38.         android:duration="100"  
  39.         android:gravity="center">  
  40.     </item>  
  41.     <item  
  42.         android:drawable="@drawable/ic_loading_white_08"  
  43.         android:duration="100"  
  44.         android:gravity="center">  
  45.     </item>  
  46.     <item  
  47.         android:drawable="@drawable/ic_loading_white_09"  
  48.         android:duration="100"  
  49.         android:gravity="center">  
  50.     </item>  
  51.     <item  
  52.         android:drawable="@drawable/ic_loading_white_10"  
  53.         android:duration="100"  
  54.         android:gravity="center">  
  55.     </item>  
  56.     <item  
  57.         android:drawable="@drawable/ic_loading_white_11"  
  58.         android:duration="100"  
  59.         android:gravity="center">  
  60.     </item>  
  61.     <item  
  62.         android:drawable="@drawable/ic_loading_white_12"  
  63.         android:duration="100"  
  64.         android:gravity="center">  
  65.     </item>  
  66.   
  67. </animation-list>  


60、 解决使用PullToRefreshListView找不到setOnItemLongClickListener方法的问题
最近在做项目的时候,使用了一个经典但是很旧的下拉刷新库,需要添加一个长按点击的监听,原来是没有这个效果需要自己去实现,

打开PullToRefreshListView这个类所继承的抽象类:PullToRefreshAdapterViewBase<T extends AbsListView> extends PullToRefreshBase<T> implements OnScrollListener   自己添加了一个方法:

[java]  view plain  copy
  1. public void setOnItemLongClickListener(OnItemLongClickListener listener){    
  2.         mRefreshableView.setOnItemLongClickListener(listener);    
  3.     }    


61、集合里面,按照对象的某个字段进行排序,这里的newData是个ArrayList的集合,里面的每个对象就是Im,im对象里面有个personStationName的字段,现在需要按照这个字段进行排序

[java]  view plain  copy
  1. <span style="white-space:pre">      </span>//得到的newData应该还要按分组名单personStationName字段进行排序 否则显示数据较为杂乱  
  2. <span style="white-space:pre">      </span>//Collections 是集合的公共类,提供各种工具,其中提供了排序方法  
  3. <span style="white-space:pre">          </span>Collections.sort(newData,new Comparator<Im>() {  
  4.                     /*  http://blog.csdn.net/lifuxiangcaohui/article/details/41543347 
  5.                      * 如果比较的是数字 
  6.                      * int compare(Student o1, Student o2) 返回一个基本类型的整型,   
  7.                      * 返回负数表示:o1 小于o2,   
  8.                      * 返回0 表示:o1和o2相等,   
  9.                      * 返回正数表示:o1大于o2。   
  10.                      */  
  11.                     @Override  
  12.                public int compare(Im im1, Im im2) {  
  13.                 //http://blog.csdn.net/one_isi_all/article/details/50036137  
  14.                 //按照机构名字进行排序  
  15.                 return im1.personStationName.compareTo(im2.personStationName);  
  16.                             }  
  17.                         });  
  18.                           

猜你喜欢

转载自blog.csdn.net/jim19890923/article/details/80306172