Android最基础知识(持续更新)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jielundewode/article/details/44171417

摘录了网上一些开发者的小知识,作为开发者必须要知道:

防止布局被弹起的键盘挤掉

安卓开发当中经常会碰到打开键盘时,通常会把布局文件挤上去,这样的应用估计100%=卸载率,其实要解决这个问题只需要在androidManiFest.xml文件相应的<activity>节点中添加android:windowSoftInputMode="adjustPan"就OK了

      官方说明:Adjustment option for softInputMode: set to have a window pan when an input method is shown, so it doesn't need to deal with resizing but just panned by the framework to ensure the current input focus is visible.(当输入法显示时,不处理大小的调整)。

还可以借助InputMethodManager动态的显示或隐藏键盘。

        InputMethodManager imm = getSystemService(Context.INPUT_METHOD_SERVICE);
        // imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
        if (imm.isActive())  //一直是true
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                    InputMethodManager.HIDE_NOT_ALWAYS);

5.获取资源的uri

Resources res = getResources() ;
int resId = R.drawable.ic_launcher ;
Uri icUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE 
+ "://"
+ res.getResourcePackageName(resId)
+ "/"
+ res.getResourceTypeName(resId)
+ "/"
+ res.getResourceEntryName(resId)) ;

6.确认Intent能否被解析

		Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:110")) ;
		ComponentName name = intent.resolveActivity(getPackageManager()) ;
		if(name == null) {
			//说明Intent不能被解析
		} else {
			//Intent可以被解析,可以调用startActivity()执行相关操作
		}

Uri与UrlEncoder

 前几日在Android开发中遇到一例时,URL中的空格符(ASCII码是0x20),在经过java.net.URLEncoder类encode以后,会变成+号,而不是%20,从而造成了server不能正确识别。

        经查,URLEncode有两个方法:

public static String encode (String s,String charsetName)
Encodes s using the Charset named bycharsetName.
 
public static String encode (String s)
Equivalent to encode(s, "UTF-8").

        第二个方法已经从Android API 1起就被弃用了,建议使用第一种方法显示的指定字符集为UTF-8,并且该编码是将空格符编码为+,而不是%20。当然,这是符合URL规范的,见RFC-1738

        要想将空格符编码为%20,就要用另一种encode,即android.net.Uri类,该类使用RFC-2396标准。语法如下:

public static String encode (String s)

Encodes characters in the given string as'%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z","a-z"), numbers ("0-9"), and unreserved characters("_-!.~'()*") intact. Encodes all other characters.

        当进行网络相关的接口实现时,还是要认真了解具体的区别,同时也建议开放平台的文档中能尽量清晰的描述协议约定,以免给开发和调试带来困难。试想,如果不是恰巧发现了这个问题,得经过多少测试才能发现这个bug呢?

修改EditText的光标颜色

EditText有一个属性:android:textCursorDrawable,这个属性是用来控制光标颜色的

android:textCursorDrawable="@null","@null"作用是让光标颜色和textcolor一样
PS:
textcursordrawable 在framework 的textview 中有这个 它代表的就是光标,是一张点9图片 ,只要去换这张图片可以了 ,这张图片在framework/core/res/res/values/themes.xml 中去更换。
在应用层也可以再editText中设置android:textCursorDrawable="@drawable/ic_png"也可以更换光标.

 

onCreate方法中获取组件的大小

		final ImageView imgView = (ImageView) findViewById(R.id.img);

		/** 第一种方法 */
		ViewTreeObserver vto2 = imgView.getViewTreeObserver();
		vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {

				imgView.getViewTreeObserver().removeOnGlobalLayoutListener(this);

				System.out.println("width:" + imgView.getWidth() + ",height:" + imgView.getHeight());
			}
		});

		/** 第二种方法 */
		ViewTreeObserver vto = imgView.getViewTreeObserver();
		vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			@Override
			public boolean onPreDraw() {
				imgView.getViewTreeObserver().removeOnPreDrawListener(this);
				System.out.println("width*:" + imgView.getWidth() + ",height*:" + imgView.getHeight());
				return true;
			}
		});

判断输入是否为中文或英文

    /**
     * 判定输入汉字
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 检测String是否全是中文
     *
     * @param name
     * @return
     */
    public static boolean checkNameChese(String name) {
        boolean res = true;
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }

    public static boolean strIsEnglish(String word) {
        //  boolean sign = true; // 初始化标志为为'true'
        for (int i = 0; i < word.length(); i++) {
            if (String.valueOf(word.charAt(i)).equals(" "))
                return true;
            if (!(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')
                    && !(word.charAt(i) >= 'a' && word.charAt(i) <= 'z')) {
                return false;
            }
        }
        return true;
    }

Ping ip

 public String Ping(String str) {  
        String resault = "";  
            Process p;  
            try {  
                //ping -c 3 -w 100  中  ,-c 是指ping的次数 3是指ping 3次 ,-w 100  以秒为单位指定超时间隔,是指超时时间为100秒   
                p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + str);  
                int status = p.waitFor();  
  
                InputStream input = p.getInputStream();  
                BufferedReader in = new BufferedReader(new InputStreamReader(input));  
                StringBuffer buffer = new StringBuffer();  
                String line = "";  
                while ((line = in.readLine()) != null){  
                  buffer.append(line);  
                }  
                System.out.println("Return ============" + buffer.toString());  
  
                if (status == 0) {  
                    resault = "success";  
                } else {  
                    resault = "faild";  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
              
  
        return resault;  
    }  

标题栏与导航栏之间出现黑线问题

<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>

扩大view点击范围

注意非常关键:一个父布局只能设置一个view的TouchDelegate,重复设置时只有最后一个生效!

 public static void expandViewTouchDelegate(final View view, final int top,  
            final int bottom, final int left, final int right) {  
  
        ((View) view.getParent()).post(new Runnable() {  
            @Override  
            public void run() {  
                Rect bounds = new Rect();  
                view.setEnabled(true);  
                view.getHitRect(bounds);  
  
                bounds.top -= top;  
                bounds.bottom += bottom;  
                bounds.left -= left;  
                bounds.right += right;  
  
                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);  
  
                if (View.class.isInstance(view.getParent())) {  
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);  
                }  
            }  
        });  
    }

打开某个app

Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
if (intent != null) {
    startActivity(intent);
} else {
    // 未安装应用
    Toast.makeText(getApplicationContext(), "哟,赶紧下载安装这个APP吧", Toast.LENGTH_LONG).show();
}

界面为ScrollView时打开界面会自动滚动到底部之解决方法

开发中遇到了这样的一个问题,界面最外层是ScrollView,然后里面有嵌套了一个ListView还有其他可以获取焦点的View,然后每次打开界面都会自动滚动到最底部,经过一番折腾,发现了一个简单的方法,

获取ScrollView里面一个上层任意view,然后调用如下方法:

view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.requestFocus();

startActivityForResult需要注意

所有需要传递或接收的 Activity 不允许设置singleInstance,或只能设为标准模式,否则系统将在 startActivityForResult() 后直接返回Activity.RESULT_CANCELED。也有文章说singleTop也不行,我在测试的时候却是可以正常运行的。而对于singleTask,设置在被启动的Activity上是不行的。

requestCode应该大于0

保留一位小数

BigDecimal decimal = new BigDecimal(String.valueOf(v));
DecimalFormat format = new DecimalFormat("####.#");
format.setRoundingMode(RoundingMode.HALF_UP);
return Double.parseDouble(format.format(decimal.doubleValue()));




 

猜你喜欢

转载自blog.csdn.net/jielundewode/article/details/44171417