zoukankan      html  css  js  c++  java
  • someone's android note

    如何在一个apk中调用另外一个apk中的activity?
       系统提供了很多可以直接调用的Activity,通过指定的Intent就可以调用,比如打开搜索的:

        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);  
        intent.putExtra(SearchManager.QUERY,"searchString")  
        startActivity(intent);  
    1. Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);  
    2. intent.putExtra(SearchManager.QUERY,"searchString")  
    3. startActivity(intent);  


         Intent.ACTION_WEB_SEARCH是一个字符串,是“搜索”这个Activity的标识,extra是传给这个activity的一些数 据。发送出这个intent之后,系统根据action字符串Intent.ACTION_WEB_SEARCH知道了是要调用哪个activity,如 果有重名,会弹出一个选择对话框。然后打开此activity,实现想要做的事情。
        那么,我们自己怎么来实现呢。
        首先,写一个activity,在AndroidManifest.xml里面的intent-filter中,给这个activity命名,

    Xml代码  收藏代码
    1. <intent-filter>  
    2.         <action android:name="chroya.foo"/>  
    3.         <category android:name="android.intent.category.DEFAULT"/>  
    4. </intent-filter>  
    1. <intent-filter>  
    2.         <action android:name="chroya.foo"/>  
    3.         <category android:name="android.intent.category.DEFAULT"/>  
    4. </intent-filter>  


        然后安装。安装完毕之后,你会发现,系统中找不到这个程序。别急,它确实安装在手机里面了,但是因为他不是main的,所以系统不会把他当做Application的入口程序。
        而要想打开这个activity,只有知道它名字的人才可以。跟系统的intent一样使用。它的名字定义为"chroya.foo",所以,这里用这个字符串就可以调用它了:

    Java代码  收藏代码
    1. Intent intent = new Intent("chroya.foo");  
    2. startActivity(intent);  
    1. Intent intent = new Intent("chroya.foo");  
    2. startActivity(intent);  


           用刚才举的那个系统的intent说明,它的activity里面使用 getIntent().getBundleExtra(SearchManager.QUERY)来接收传递进来的搜索字符串参数。而这个 SearchManager.QUERY是关键字。如果要自己实现这种功能,只需要定义好关键字,然后从BundleExtra中取就行了。

    如何获取屏幕上正显示的activity?
           用过ActivityManager的童鞋估计都知道,可以从ActivityManager里面可以获取到当前运行的所有任务,所有进程和所有服务,这是任务管理器的核心。
             那么,从里面我们可以发掘点什么出来吗?
             仔细看getRunningTasks的文档,里面说获取的是系统中"running"的所有task,"running"状态包括已经被系统冻结的task。而且返回的这个列表是按照顺序排列的,也就是说第一个肯定比第二个后运行。
              getRunningTasks有个整型参数,表示返回列表的最大个数。那么,我们如果把1作为参数给进去,那么他返回的task就是当前运行的那个 task,然后从task中获取到最顶层的activity,这个activity就是当前显示给用户的那个activity了。

    Java代码  收藏代码
    1. ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);  
    2. ComponentName cn = am.getRunningTasks(1).get(0).topActivity;  
    3. Log.d("""pkg:"+cn.getPackageName());  
    4. Log.d("""cls:"+cn.getClassName());   
    1. ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);  
    2. ComponentName cn = am.getRunningTasks(1).get(0).topActivity;  
    3. Log.d("""pkg:"+cn.getPackageName());  
    4. Log.d("""cls:"+cn.getClassName());   


           至于这个能做什么,嘿嘿,我相信你知道的。

    如何判断一个activity是否存在于系统中?
    已知包名和类名,如何判断这个activity是否在系统中存在呢?很简单,通过intent就行。

    Java代码  收藏代码
    1. Intent intent = new Intent();  
    2. intent.setClassName("包名""类名");        
    3. if(getPackageManager().resolveActivity(intent, 0) == null) {  
    4.     //说明系统中不存在这个activity  
    5. }  
    1. Intent intent = new Intent();  
    2. intent.setClassName("包名""类名");        
    3. if(getPackageManager().resolveActivity(intent, 0) == null) {  
    4.     //说明系统中不存在这个activity  
    5. }  



    如何让应用程序动态全屏和退出全屏?
        让程序全屏的方法,大家都知道,那是静态的,程序运行之初就申明了。但是如果有这样的需求:要在程序运行的过程中,执行了某个操作而使之全屏,然后还需要退出全屏,怎么做?
        如下:

    Java代码  收藏代码
    1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
    2. attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;  
    3. getWindow().setAttributes(attrs);  
    4. getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  
    1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
    2. attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;  
    3. getWindow().setAttributes(attrs);  
    4. getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  


        修改window的LayoutParams参数,然后加上FLAG_LAYOUT_NO_LIMITS标志,就OK了。window会自动重新布局,呈现全屏的状态。
        要退出全屏,只需要清除刚才加上的FLAG_FULLSCREEN参数,然后去掉FLAG_LAYOUT_NO_LIMITS标志。
        如下:

    Java代码  收藏代码
    1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
    2. attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);  
    3. getWindow().setAttributes(attrs);  
    4. getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  
    1. WindowManager.LayoutParams attrs = getWindow().getAttributes();  
    2. attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);  
    3. getWindow().setAttributes(attrs);  
    4. getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);  



    如何获取状态栏和标题栏的高度?
    1.获取状态栏高度:
    decorView 是window中的最顶层view,可以从window中获取到decorView,然后decorView有个 getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。于是,我们就可以算出状态栏的高 度了。

    Java代码  收藏代码
    1. Rect frame = new Rect();  
    2. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
    3. int statusBarHeight = frame.top;   
    1. Rect frame = new Rect();  
    2. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
    3. int statusBarHeight = frame.top;   


    2.获取标题栏高度:
    getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。

    Java代码  收藏代码
    1. int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
    2. //statusBarHeight是上面所求的状态栏的高度  
    3. int titleBarHeight = contentTop - statusBarHeight;  
    1. int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
    2. //statusBarHeight是上面所求的状态栏的高度  
    3. int titleBarHeight = contentTop - statusBarHeight;  



    如何将一个视窗(windows)盖在整个Application的最上面?

    Java代码  收藏代码
    1.  private ImageView waitView;  
    2. private final void showWaiting() {  
    3.  try {  
    4. WindowManager.LayoutParams lp = null;  
    5. lp = new WindowManager.LayoutParams(  
    6. ViewGroup.LayoutParams.WRAP_CONTENT,  
    7. ViewGroup.LayoutParams.WRAP_CONTENT,  
    8. WindowManager.LayoutParams.TYPE_TOAST ,  
    9. WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  
    10. | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE  
    11. | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,  
    12. PixelFormat.TRANSLUCENT  
    13. | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) ;  
    14. WindowManager mWindowManager = (WindowManager) G.appInstance  
    15. .getSystemService(Context.WINDOW_SERVICE);  
    16. if (waitView == null) {  
    17. LayoutInflater inflate = (LayoutInflater) G.appInstance  
    18. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
    19. waitView = (ImageView) inflate.inflate(R.layout.waiting_layout,  
    20. null);  
    21. }  
    22. mWindowManager.addView(waitView, lp);  
    23. catch (Throwable e) {  
    24. }  
    25. }  
    1.  private ImageView waitView;  
    2. private final void showWaiting() {  
    3.  try {  
    4. WindowManager.LayoutParams lp = null;  
    5. lp = new WindowManager.LayoutParams(  
    6. ViewGroup.LayoutParams.WRAP_CONTENT,  
    7. ViewGroup.LayoutParams.WRAP_CONTENT,  
    8. WindowManager.LayoutParams.TYPE_TOAST ,  
    9. WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  
    10. | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE  
    11. | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,  
    12. PixelFormat.TRANSLUCENT  
    13. | WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW) ;  
    14. WindowManager mWindowManager = (WindowManager) G.appInstance  
    15. .getSystemService(Context.WINDOW_SERVICE);  
    16. if (waitView == null) {  
    17. LayoutInflater inflate = (LayoutInflater) G.appInstance  
    18. .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
    19. waitView = (ImageView) inflate.inflate(R.layout.waiting_layout,  
    20. null);  
    21. }  
    22. mWindowManager.addView(waitView, lp);  
    23. catch (Throwable e) {  
    24. }  
    25. }  


    注意:
    1. 要将window的类型配置成Type_toast。
    2.G.appInstance 上下文需要使用Application的context.

    如何判断快捷方式是否已经创建?
    快捷方式信息是保存在com.android.launcher的launcher.db的favorites表中

    Java代码  收藏代码
    1.     boolean isInstallShortcut = false ;  
    2.     final ContentResolver cr = context.getContentResolver();  
    3.     final String AUTHORITY = "com.android.launcher.settings";  
    4.     final Uri CONTENT_URI = Uri.parse("content://" +  
    5.                      AUTHORITY + "/favorites?notify=true");  
    6.       
    7.     Cursor c = cr.query(CONTENT_URI,  
    8.     new String[] {"title","iconResource" },  
    9.     "title=?",  
    10.     new String[] {"XXX" }, null);//XXX表示应用名称。  
    11.             if(c!=null && c.getCount()>0){  
    12.         isInstallShortcut = true ;  
    13.     }  
    14.     /*try { 
    15.         while (c.moveToNext()) { 
    16.                                     String tmp = ""; 
    17.             tmp = c.getString(0); 
    18.         } 
    19.         } catch (Exception e) { 
    20.  
    21.         } finally { 
    22.             c.close(); 
    23.         }*/  
    24.     return isInstallShortcut ;  
    25. }  
    1.     boolean isInstallShortcut = false ;  
    2.     final ContentResolver cr = context.getContentResolver();  
    3.     final String AUTHORITY = "com.android.launcher.settings";  
    4.     final Uri CONTENT_URI = Uri.parse("content://" +  
    5.                      AUTHORITY + "/favorites?notify=true");  
    6.       
    7.     Cursor c = cr.query(CONTENT_URI,  
    8.     new String[] {"title","iconResource" },  
    9.     "title=?",  
    10.     new String[] {"XXX" }, null);//XXX表示应用名称。  
    11.             if(c!=null && c.getCount()>0){  
    12.         isInstallShortcut = true ;  
    13.     }  
    14.     /*try { 
    15.         while (c.moveToNext()) { 
    16.                                     String tmp = ""; 
    17.             tmp = c.getString(0); 
    18.         } 
    19.         } catch (Exception e) { 
    20.  
    21.         } finally { 
    22.             c.close(); 
    23.         }*/  
    24.     return isInstallShortcut ;  
    25. }  


    要有权限:
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
    注意:2.2及其之后的版本不能用这个方法判断!(虽然在launcher.db数据库里还有favorites这个表)

    如何让ListView中TextView的字体颜色跟随焦点的变化?
    我们通常需要ListView中某一项选中时,他的字体颜色和原来的不一样。 如何设置字体的颜色呢? 在布局文件中TextColor一项来设置颜色,但是不是只设置一种颜色,而是在不同的条件下设置不同的颜色: 下面是个例子:

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="utf-8" ?>  
    2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
    3. <item android:state_enabled="false" android:color="@color/orange"></item>  
    4. <item android:state_window_focused="false" android:color="@color/orange"></item>  
    5. <item android:state_pressed="true" android:color="@color/white"></item>  
    6. <item android:state_selected="true" android:color="@color/white"></item>  
    7. <item android:color="@color/orange"></item>  
    8. </selector>   
    9. 在获取焦点或者选中的情况下设置为白色,其他情况设置为橘黄色。  
    1. <?xml version="1.0" encoding="utf-8" ?>  
    2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
    3. <item android:state_enabled="false" android:color="@color/orange"></item>  
    4. <item android:state_window_focused="false" android:color="@color/orange"></item>  
    5. <item android:state_pressed="true" android:color="@color/white"></item>  
    6. <item android:state_selected="true" android:color="@color/white"></item>  
    7. <item android:color="@color/orange"></item>  
    8. </selector>   
    9. 在获取焦点或者选中的情况下设置为白色,其他情况设置为橘黄色。  




    如何在android的一个应用中调用另外一个应用?

    Java代码  收藏代码
    1. Intent intent = new Intent();  
    2. //第一个参数另一个应用的包名,第二个是需要启动的类  
    3. intent.setComponent(new ComponentName("com.Ex03_03","com.Ex03_03.Ex03_03"));  
    4. startActivity(intent);  
    1. Intent intent = new Intent();  
    2. //第一个参数另一个应用的包名,第二个是需要启动的类  
    3. intent.setComponent(new ComponentName("com.Ex03_03","com.Ex03_03.Ex03_03"));  
    4. startActivity(intent);  



    如何遍历listView 的的单选框?

    Java代码  收藏代码
    1. ListView listView = (ListView)findViewById(R.id.配置文件中ListView的ID);  
    2. //全选遍历ListView的选项,每个选项就相当于布局配置文件中的RelativeLayout  
    3. for(int i = 0; i < listView.getChildCount(); i++){  
    4.       View view = listView.getChildAt(i);  
    5.       CheckBox cb = (CheckBox)view.findViewById(R.id.CheckBoxID);  
    6.       cb.setChecked(true);  
    7. }  
    1. ListView listView = (ListView)findViewById(R.id.配置文件中ListView的ID);  
    2. //全选遍历ListView的选项,每个选项就相当于布局配置文件中的RelativeLayout  
    3. for(int i = 0; i < listView.getChildCount(); i++){  
    4.       View view = listView.getChildAt(i);  
    5.       CheckBox cb = (CheckBox)view.findViewById(R.id.CheckBoxID);  
    6.       cb.setChecked(true);  
    7. }  



    如何获取程序版本号?

    Java代码  收藏代码
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    3.    package="com.yourcompany.yourapp"   
    4.    android:versionCode="109"  
    5.    android:versionName="0.1.6.109 dev">  
    6.    ...  
    7. </manifest>  
    8.  public static int getVersionCode(Context context) {  
    9.    PackageManager pm = context.getPackageManager();  
    10.    try {  
    11.       PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);  
    12.       return pi.versionCode;  
    13.    } catch (NameNotFoundException ex) {}  
    14.    return 0;  
    15. }  
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    3.    package="com.yourcompany.yourapp"   
    4.    android:versionCode="109"  
    5.    android:versionName="0.1.6.109 dev">  
    6.    ...  
    7. </manifest>  
    8.  public static int getVersionCode(Context context) {  
    9.    PackageManager pm = context.getPackageManager();  
    10.    try {  
    11.       PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);  
    12.       return pi.versionCode;  
    13.    } catch (NameNotFoundException ex) {}  
    14.    return 0;  
    15. }  



    如何让Toast充满全屏?

    Java代码  收藏代码
    1. Toast t = Toast.makeText(this"Hello", Toast.LENGTH_SHORT);  
    2. t.setGravity(Gravity.FILL_HORIZONTAL, 00);  
    1. Toast t = Toast.makeText(this"Hello", Toast.LENGTH_SHORT);  
    2. t.setGravity(Gravity.FILL_HORIZONTAL, 00);  



    如何更高效简单的实现界面中的分隔线?

    Java代码  收藏代码
    1. <View    
    2.     android:layout_width="fill_parent"     
    3.     android:layout_height="1px"     
    4.     android:background="?android:attr/listDivider"     
    5. />  
    1. <View    
    2.     android:layout_width="fill_parent"     
    3.     android:layout_height="1px"     
    4.     android:background="?android:attr/listDivider"     
    5. />  



    如何发起或删除另一个程序?

    Java代码  收藏代码
    1. final Intent intent = new Intent(Intent.ACTION_MAIN, null);  
    2. intent.addCategory(Intent.CATEGORY_LAUNCHER);  
    3. final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");  
    4. intent.setComponent(cn);  
    5. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    6. startActivity( intent);  
    1. final Intent intent = new Intent(Intent.ACTION_MAIN, null);  
    2. intent.addCategory(Intent.CATEGORY_LAUNCHER);  
    3. final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.fuelgauge.PowerUsageSummary");  
    4. intent.setComponent(cn);  
    5. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    6. startActivity( intent);  
    Java代码  收藏代码
    1. //ComponentName 两个参数一个是包名 一个是包下的主类  
    2. Uri uri = Uri.fromParts("package",“Your Package name here”, null);  
    3. Intent deleteIntent = new Intent(Intent.ACTION_DELETE, uri);  
    4. startActivity(deleteIntent);  
    1. //ComponentName 两个参数一个是包名 一个是包下的主类  
    2. Uri uri = Uri.fromParts("package",“Your Package name here”, null);  
    3. Intent deleteIntent = new Intent(Intent.ACTION_DELETE, uri);  
    4. startActivity(deleteIntent);  



    如何为TextView添加阴影?
    values/styles

    Xml代码  收藏代码
    1. <style name="AudioFileInfoOverlayText">   
    2.     <item name="android:paddingLeft">4px</item>   
    3.     <item name="android:paddingBottom">4px</item>   
    4.     <item name="android:textColor">#ffffffff</item>   
    5.     <item name="android:textSize">12sp</item>   
    6.     <item name="android:shadowColor">#ff00ff00</item>   
    7.     <item name="android:shadowDx">5</item>   
    8.     <item name="android:shadowDy">3</item>   
    9.     <item name="android:shadowRadius">6</item>  
    10. </style>  
    1. <style name="AudioFileInfoOverlayText">   
    2.     <item name="android:paddingLeft">4px</item>   
    3.     <item name="android:paddingBottom">4px</item>   
    4.     <item name="android:textColor">#ffffffff</item>   
    5.     <item name="android:textSize">12sp</item>   
    6.     <item name="android:shadowColor">#ff00ff00</item>   
    7.     <item name="android:shadowDx">5</item>   
    8.     <item name="android:shadowDy">3</item>   
    9.     <item name="android:shadowRadius">6</item>  
    10. </style>  


    <TextView android:id="@+id/info"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           style="@style/AudioFileInfoOverlayText"
           android:text="aaaa"
           android:gravity="center" />

    如何监测是否静音?

    Java代码  收藏代码
    1. AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);   
    2. switch (am.getRingerMode()) {   
    3.     case AudioManager.RINGER_MODE_SILENT:   
    4.         Log.i("MyApp","Silent mode");   
    5.         break;   
    6.     case AudioManager.RINGER_MODE_VIBRATE:   
    7.         Log.i("MyApp","Vibrate mode");   
    8.         break;   
    9.     case AudioManager.RINGER_MODE_NORMAL:   
    10.         Log.i("MyApp","Normal mode");   
    11.         break;   
    12. }   
    1. AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);   
    2. switch (am.getRingerMode()) {   
    3.     case AudioManager.RINGER_MODE_SILENT:   
    4.         Log.i("MyApp","Silent mode");   
    5.         break;   
    6.     case AudioManager.RINGER_MODE_VIBRATE:   
    7.         Log.i("MyApp","Vibrate mode");   
    8.         break;   
    9.     case AudioManager.RINGER_MODE_NORMAL:   
    10.         Log.i("MyApp","Normal mode");   
    11.         break;   
    12. }   



    如何设置控件的随机显示位置?

    Java代码  收藏代码
    1. RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();  
    2. parms.leftMargin = (int) (Math.random() * 320);  
    3. parms.topMargin = (int) (Math.random() * 480);  
    4. img.setLayoutParams(parms);          
    5. img.invalidate();  
    1. RelativeLayout.LayoutParams parms=(RelativeLayout.LayoutParams)img.getLayoutParams();  
    2. parms.leftMargin = (int) (Math.random() * 320);  
    3. parms.topMargin = (int) (Math.random() * 480);  
    4. img.setLayoutParams(parms);          
    5. img.invalidate();  



    如何让软键盘显示/消失?

    Java代码  收藏代码
    1. InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);      
    2. View view = getCurrentFocus();      
    3. if (view != null){      
    4.      // imm.showSoftInput(view, 0); //显示软键盘      
    5.       imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);    
    6.      // imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隐藏软键盘  // InputMethodManager.HIDE_NOT_ALWAYS);    
    7. }    
    1. InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);      
    2. View view = getCurrentFocus();      
    3. if (view != null){      
    4.      // imm.showSoftInput(view, 0); //显示软键盘      
    5.       imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);    
    6.      // imm.hideSoftInputFromWindow(view.getWindowToken(), 0);//隐藏软键盘  // InputMethodManager.HIDE_NOT_ALWAYS);    
    7. }    



    如何为Activity屏幕的标题栏添加图标?

    Java代码  收藏代码
    1. @Override    
    2. public void onCreate(Bundle icicle) {    
    3.     super.onCreate(icicle);    
    4.     Window win = getWindow();    
    5.     win.requestFeature(Window.FEATURE_LEFT_ICON);        
    6.     setContentView(R.layout.mylayout);     
    7.     win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);    
    8. }  
    1. @Override    
    2. public void onCreate(Bundle icicle) {    
    3.     super.onCreate(icicle);    
    4.     Window win = getWindow();    
    5.     win.requestFeature(Window.FEATURE_LEFT_ICON);        
    6.     setContentView(R.layout.mylayout);     
    7.     win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);    
    8. }  


    要注意的是,win.setFeatureDrawableResource必须在setContentView之后,不然就没有效果。

    如何让ListView自动滚动?
    注意stackFromBottom以及transcriptMode这两个属性。类似Market客户端的低端不断滚动。
    <ListView android:id="listCWJ" 
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent" 
         android:stackFromBottom="true"   
         android:transcriptMode="alwaysScroll" 
    />

    如何设置桌面壁纸?
    希望在你的程序中能设置桌面壁纸吗?很简单,首先我们需要取得设置壁纸的权限。和其它权限一样,只要在配置文件中加上以下配置信息即可。
    <uses-permission android:name="android.permission.SET_WALLPAPER" />
    然后在程序中调用如下代码即可设置桌面壁纸:
    getApplicationContext().setWallpaper(bitmap)

    如何在标题栏(titlebar)显示进度条?

    Java代码  收藏代码
    1. protected void onCreate(Bundle savedInstanceState) {  
    2.         super.onCreate(savedInstanceState);  
    3.         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先给Activity注册界面进度条功能  
    4.         setContentView(R.layout.main);  
    5.         setProgressBarIndeterminateVisibility(true);//在需要显示进度条的时候调用这个方法  
    6.         setProgressBarIndeterminateVisibility(false);//在不需要显示进度条的时候调用这个方法  
    7. }  
    1. protected void onCreate(Bundle savedInstanceState) {  
    2.         super.onCreate(savedInstanceState);  
    3.         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//先给Activity注册界面进度条功能  
    4.         setContentView(R.layout.main);  
    5.         setProgressBarIndeterminateVisibility(true);//在需要显示进度条的时候调用这个方法  
    6.         setProgressBarIndeterminateVisibility(false);//在不需要显示进度条的时候调用这个方法  
    7. }  



    如何去掉activity顶部的gradient?
    <style name="Theme.Foo" parent="android:style/Theme.Light">
        <item name="android:windowContentOverlay">@null</item>
    </style>
    <activity android:name=".FooActivity"
              android:theme="@style/Theme.Foo"> ...
    http://wang-peng1.iteye.com/blog/680015

    如何让ScrollView强制滑到底部?
    scroll.fullScroll(View.FOCUS_DOWN) 就可以了

    如何ViewFlipper去掉多余空间?
    ViewFlipper flipper = (ViewFlipper)findViewById(R.id.flipper);
    flipper.setMeasureAllChildren(false);

    如何去掉tabhost横线?

    Java代码  收藏代码
    1. 很简单 简单的有时候是因为我们太浮躁  
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"       
    3.     android:orientation="vertical"   
    4.     android:layout_width="fill_parent"   
    5.     android:layout_height="fill_parent"   
    6.    
    7.     android:gravity="center_horizontal">         
    8.    <TabHost    
    9.     android:id="@android:id/tabhost"       
    10.     android:layout_width="fill_parent"   
    11.     android:layout_height="fill_parent"   
    12.     >   
    13. ...   
    14. ...   
    15. ...   
    16.     </TabHost>   
    17.     </LinearLayout>   
    18. 外面加一层LinearLayout  
    1. 很简单 简单的有时候是因为我们太浮躁  
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"       
    3.     android:orientation="vertical"   
    4.     android:layout_width="fill_parent"   
    5.     android:layout_height="fill_parent"   
    6.    
    7.     android:gravity="center_horizontal">         
    8.    <TabHost    
    9.     android:id="@android:id/tabhost"       
    10.     android:layout_width="fill_parent"   
    11.     android:layout_height="fill_parent"   
    12.     >   
    13. ...   
    14. ...   
    15. ...   
    16.     </TabHost>   
    17.     </LinearLayout>   
    18. 外面加一层LinearLayout  



    如何判断国家?

    Java代码  收藏代码
    1. String locale = context.getResources().getConfiguration().locale.getCountry();    
    2. String locale = context.getResources().getConfiguration().locale.getDisplayCountry();   
    3. TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);   
    4. String countryCode = tm.getSimCountryIso();   
    1. String locale = context.getResources().getConfiguration().locale.getCountry();    
    2. String locale = context.getResources().getConfiguration().locale.getDisplayCountry();   
    3. TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);   
    4. String countryCode = tm.getSimCountryIso();   



    如何让屏幕保持一直亮?

    Java代码  收藏代码
    1. @Override  
    2.     protected void onCreate(Bundle icicle) {  
    3.         super.onCreate(icicle);  
    4.   
    5.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
    6.     }  
    1. @Override  
    2.     protected void onCreate(Bundle icicle) {  
    3.         super.onCreate(icicle);  
    4.   
    5.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
    6.     }  


    http://wang-peng1.iteye.com/blog/769561

    如何检查sim卡状态?

    Java代码  收藏代码
    1. TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);  
    2.     int simState = telMgr.getSimState();  
    3.             switch (simState) {  
    4.                 case TelephonyManager.SIM_STATE_ABSENT:  
    5.                     // do something  
    6.                     break;  
    7.                 case TelephonyManager.SIM_STATE_NETWORK_LOCKED:  
    8.                     // do something  
    9.                     break;  
    10.                 case TelephonyManager.SIM_STATE_PIN_REQUIRED:  
    11.                     // do something  
    12.                     break;  
    13.                 case TelephonyManager.SIM_STATE_PUK_REQUIRED:  
    14.                     // do something  
    15.                     break;  
    16.                 case TelephonyManager.SIM_STATE_READY:  
    17.                     // do something  
    18.                     break;  
    19.                 case TelephonyManager.SIM_STATE_UNKNOWN:  
    20.                     // do something  
    21.                     break;  
    22.             }  
    1. TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);  
    2.     int simState = telMgr.getSimState();  
    3.             switch (simState) {  
    4.                 case TelephonyManager.SIM_STATE_ABSENT:  
    5.                     // do something  
    6.                     break;  
    7.                 case TelephonyManager.SIM_STATE_NETWORK_LOCKED:  
    8.                     // do something  
    9.                     break;  
    10.                 case TelephonyManager.SIM_STATE_PIN_REQUIRED:  
    11.                     // do something  
    12.                     break;  
    13.                 case TelephonyManager.SIM_STATE_PUK_REQUIRED:  
    14.                     // do something  
    15.                     break;  
    16.                 case TelephonyManager.SIM_STATE_READY:  
    17.                     // do something  
    18.                     break;  
    19.                 case TelephonyManager.SIM_STATE_UNKNOWN:  
    20.                     // do something  
    21.                     break;  
    22.             }  



    如何从SMS获取联系人信息?

    Java代码  收藏代码
    1. ContactItem getContactByAddr(Context context, final SMSItem sms) {    
    2.     Uri personUri = Uri.withAppendedPath(    
    3.             ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);    
    4.     Cursor cur = context.getContentResolver().query(personUri,    
    5.             new String[] { PhoneLookup.DISPLAY_NAME },    
    6.             nullnullnull );    
    7.     if( cur.moveToFirst() ) {    
    8.         int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);    
    9.         ContactItem item = new ContactItem();    
    10.         item.mName = cur.getString(nameIdx);    
    11.        cur.close();    
    12.        return item;    
    13.    }    
    14.    return null;    
    15. }  
    1. ContactItem getContactByAddr(Context context, final SMSItem sms) {    
    2.     Uri personUri = Uri.withAppendedPath(    
    3.             ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);    
    4.     Cursor cur = context.getContentResolver().query(personUri,    
    5.             new String[] { PhoneLookup.DISPLAY_NAME },    
    6.             nullnullnull );    
    7.     if( cur.moveToFirst() ) {    
    8.         int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);    
    9.         ContactItem item = new ContactItem();    
    10.         item.mName = cur.getString(nameIdx);    
    11.        cur.close();    
    12.        return item;    
    13.    }    
    14.    return null;    
    15. }  



    如何在使用gallery在flinging拖动时候不出现选择的情况?
    这时候需要注意使用
    gallery.setCallbackDuringFling(false)

    TabHost组件,怎么调整tab的高度?

    Java代码  收藏代码
    1. TabWidget tabWidget = mTabHost.getTabWidget();  
    2. int count = tabWidget.getChildCount();  
    3. for(int i = 0;i<count;i++){  
    4.         View view = tabWidget.getChildTabViewAt(i);// tabWidget.getChildAt(i);  
    5.         view.getLayoutParams().height = 40;  
    6. }  
    1. TabWidget tabWidget = mTabHost.getTabWidget();  
    2. int count = tabWidget.getChildCount();  
    3. for(int i = 0;i<count;i++){  
    4.         View view = tabWidget.getChildTabViewAt(i);// tabWidget.getChildAt(i);  
    5.         view.getLayoutParams().height = 40;  
    6. }  



    如何模拟SDcard?
    看图:


    应该能看明白。

    如何自定义ListView行间的分割线?
    在Android平台中系统控件提供了灵活的自定义选项,所有基于ListView或者说AbsListView实现的widget控件均可以通过下面的方法设置行间距的分割线,分割线可以自定义颜色、或图片。
    在 ListView中我们使用属性   android:divider="#FF0000" 定义分隔符为红色,当然这里值可以指向一个drawable图片对象,如果使用了图片可能高度大于系统默认的像素,可以自己设置高度比如6个像素   android:dividerHeight="6px" ,Android开发网提示当然在Java中ListView也有相关方法可以设置。

    如何在EditText中显示隐藏Android输入法窗口?
    细心的网友可能发现我们在使用EditText时,会自动的弹出输入法面板,这里我们提供多种方法可以不让程序默认升起IME窗口。
    1.让EditText失去焦点,使用EditText的clearFocus方法
    2. 强制隐藏Android输入法窗口,在IME类中我们通过
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 实例化输入法控制对象,通过hideSoftInputFromWindow来控制,其中第一个参数绑定的为需要隐藏输入法的EditText对象,比如 imm.hideSoftInputFromWindow(etAndroid123.getWindowToken(), 0);

    如何实现TextView多行本文滚动?
    Android中我们为了实现文本的滚动可以在ScrollView中嵌入一个TextView,其实TextView自己也可以实现多行滚动的,毕竟ScrollView必须只能有一个直接的子类布局。只要在layout中简单设置几个属性就可以轻松实现
      <TextView 
        android:id="@+id/tvCWJ" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:scrollbars="vertical"   <!--垂直滚动条 -->
        android:singleLine="false"       <!--实现多行 -->
        android:maxLines="15"            <!--最多不超过15行 -->
        android:textColor="#FF0000"
        />
    当然我们为了让TextView动起来,还需要用到TextView的setMovementMethod方法设置一个滚动实例,代码如下
    TextView tvAndroid123 = (TextView)findViewById(R.id.tvCWJ);  
    tvAndroid123.setMovementMethod(ScrollingMovementMethod.getInstance());

    如何对View截屏?
    对于自己的View实现一些绘图或子类化的技术时可以不用系统级这样的方法,我们可以通过
    view.setDrawingCacheEnabled(true); //其中View是你需要截图的的View
    Bitmap bm = view.getDrawingCache();

    如何区别onRetainNonConfigurationInstance和getLastNonConfigurationInstance?
    很 多网友可能知道Android横竖屏切换时会触发onSaveInstanceState,而还原时会产生 onRestoreInstanceState,但是Android的Activity类还有一个方法名为 onRetainNonConfigurationInstance和getLastNonConfigurationInstance这两个方法。
    我们可以通过  onRetainNonConfigurationInstance 代替 onSaveInstanceState,比如距离2
    @Override
      public Object onRetainNonConfigurationInstance()
    {   
           //这里需要保存的内容,在切换时不是bundle了,我们可以直接通过Object来代替
          return obj;
    }

    在恢复窗口时,我们可以不使用 onRestoreInstanceState,而代替的是 getLastNonConfigurationInstance 方法。我们可以直接在onCreate中使用,比如
    Object obj = getLastNonConfigurationInstance();     最终obj的内容就是上次切换时的内容。
    这里Android123提醒大家,每次Activity横竖屏切换时onCreate方法都会被触发。

    如何区别AsyncTask和Thread+Handler?
    很 多网友可能发现Android平台很多应用使用的都是AsyncTask,而并非Thread和Handler去更新UI,这里Android123给大 家说下他们到底有什么区别,我们平时应该使用哪种解决方案。从Android 1.5开始系统将AsyncTask引入到android.os包中,过去在很早1.1和1.0 SDK时其实官方将其命名为UserTask,其内部是JDK 1.5开始新增的concurrent库,做过J2EE的网友可能明白并发库效率和强大性,比Java原始的Thread更灵活和强大,但对于轻量级的使 用更为占用系统资源。Thread是Java早期为实现多线程而设计的,比较简单不支持concurrent中很多特性在同步和线程池类中需要自己去实现 很多的东西,对于分布式应用来说更需要自己写调度代码,而为了Android UI的刷新Google引入了Handler和Looper机制,它们均基于消息实现,有事可能消息队列阻塞或其他原因无法准确的使用。

      Android开发网推荐大家使用AsyncTask代替Thread+Handler的方式,不仅调用上更为简单,经过实测更可靠一些,Google在 Browser中大量使用了异步任务作为处理耗时的I/O操作,比如下载文件、读写数据库等等,它们在本质上都离不开消息,但是AsyncTask相比 Thread加Handler更为可靠,更易于维护,但AsyncTask缺点也是有的比如一旦线程开启即dobackground方法执行后无法给线程 发送消息,仅能通过预先设置好的标记来控制逻辑,当然可以通过线程的挂起等待标志位的改变来通讯,对于某些应用Thread和Handler以及 Looper可能更灵活。

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

    Java代码  收藏代码
    1. Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);  
    2.     Drawable[] array = new Drawable[3];  
    3.      array[0] = new PaintDrawable(Color.BLACK); //黑色  
    4.      array[1] = new PaintDrawable(Color.WHITE); //白色     
    5.      array[2] = new BitmapDrawable(bm); //位图资源          
    6.     LayerDrawable ld = new LayerDrawable(array); //参数为上面的Drawable数组  
    7.     ld.setLayerInset(11111);  //第一个参数1代表数组的第二个元素,为白色  
    8.     ld.setLayerInset(22222); //第一个参数2代表数组的第三个元素,为位图资源  
    9.     mImageView.setImageDrawable(ld);  
    1. Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.cwj);  
    2.     Drawable[] array = new Drawable[3];  
    3.      array[0] = new PaintDrawable(Color.BLACK); //黑色  
    4.      array[1] = new PaintDrawable(Color.WHITE); //白色     
    5.      array[2] = new BitmapDrawable(bm); //位图资源          
    6.     LayerDrawable ld = new LayerDrawable(array); //参数为上面的Drawable数组  
    7.     ld.setLayerInset(11111);  //第一个参数1代表数组的第二个元素,为白色  
    8.     ld.setLayerInset(22222); //第一个参数2代表数组的第三个元素,为位图资源  
    9.     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即可实现简单的图片合成。

     
  • 相关阅读:
    人工智能应用卷积神经网络对食道癌的诊断结果--笔记
    面向对象设计
    结构化软件测试----白盒测试技术
    内聚与耦合的实例分析
    图书预定系统
    SQL小技巧
    Keras中RNN、LSTM和GRU的参数计算
    Keras+Tensorboard
    Floyd算法
    生成随机整数
  • 原文地址:https://www.cnblogs.com/royi123/p/3001490.html
Copyright © 2011-2022 走看看