记:Android 知识点整理 20140329

1、通过代码设置添加组件并设置属性:
    LayoutParams.addRule方法可以设置布局相关的所有属性。
    1)、装载一个布局;
    2)、创建一个view组件;
    3)、创建一个LayoutParams对象;
    4)、调用addRule方法设置属性;可多次调用设置多个属性;
    5)、更新属性值,即调用view组件的setLayoutParams方法;
    6)、添加到布局中;

2、截取应用中组件保存到图片(必须调用measure和layout方法后才能得到bitmap):
    1)、得到要截取的组件view;
    2)、打开图像缓存,view.setDrawingCacheEnabled(true);
    3)、测量view大小,view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    4)、发送位置和尺寸到view及其子view,view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    5)、获取view的截图,Bitmap bitmap = view.getDrawingCache();
    6)、创建输出流,FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
    7)、将bitmap压缩成png图像,bitmap.compress(CompressFormat.PNG, 100, fos);
    8)、关闭输出流,fos.close();

3、设置窗口背景渐变色(也可以设置按钮等其他组件的背景色):
    1)、设置从上倒下的渐变色,上方红色,下方黄色
    GradientDrawable gradientDrawable = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{Color.RED, Color.YELLOW});
    2)、将渐变色应用到窗口
    getWindow().setBackgroundDrawable(gradientDrawable);

4、android:layout_weight属性,用来设置组件的权重;
    横排显示3个组件,第一个和第三个分别占总宽度的四分之一,中间组件占总宽度的四分之二:
    第一个,android:layout_weight=2
    第二个,android:layout_weight=1
    第三个,android:layout_weight=2
    这样既可达到目的,个人猜测权重为1的组件占用屏幕的大小是其他组件的权重的倍数;比如第一个是3时,权重为1的第二个的宽度是权重为3的第一个组件宽度的3倍(有待验证);

5、LinearLayout内的组件是否显示的问题:
    如果LinearLayout内的组件的宽度和高度都设置成match_parent,且都没有设置权重,则第一个组件会占据整个LinearLayout,第二个组件不会显示出来;解决方法是为组件设置android:layout_weight属性值。

6、在EditText组件中显示提示文本,用户在提示文本后面开始输入
    第一种方法:在EditText组件中使用android:drawableLeft属性加载一个drawable资源,当作提示文本,也就是要把提示文本做成图片,该方法很不灵活.
    第二种方法:编写一个继承自EditText的类,复写onDraw(Canvas canvas)方法:
    @Override
    protected void onDraw(Canvas canvas)
    {
        Paint paint = new Paint();
        paint.setTextSize(18);
        paint.setColor(Color.GRAY);
        canvas.drawText("提示:", 2, getHeight()/2+5, paint);
        super.onDraw(canvas);
    }
    然后在组件的属性中设置android:paddingLeft的值为提示文本的宽度值。从距离左侧边缘一定距离开始输入。

7、android:padding属性和android:layout_margin属性的区别
    前者用来设置view内部组件或内容距离view边缘的距离;后者用来设置view边缘距离其他组件或父容器边缘的距离。

8、尺寸计量单位
    共六种:px(像素)、in(英寸)、mm(毫米)、pt(一个物理点,1/72英寸)、dp(与密度无关的像素)、sp(与比例无关的像素)。
    其中px、in、mm和pt用来设置绝对尺寸,不会随着屏幕分辨率的变化而调整,而dp和sp会随着屏幕分辨率的变化进行调整。
    所以除了特殊需要,建议使用dp作为view的尺寸单位,使用sp作为text的尺寸单位。

9、android:layout_gravity
    当父容器为LinearLayout时:
        该属性在水平线型布局中使用时,值设置为垂直方向的值才起作用;
        在垂直线型布局中使用时,值设置为水平方向的值才起作用。
    在FrameaLyout布局中均起作用。

10、LinearLayout的android:orientation属性
    默认为水平线型布局,值为verticalsh时为垂直线型布局;

11、重用布局文件
    使用include标签引用其他布局文件,并可使用android:id属性覆盖掉被引用布局中顶层节点的android:id属性:
    <include android:id="@+id/layout1" layout="@layout/mylayout" />

12、布局文件的根节点使用FrameLayout可以吗?
    无论布局文件的根节点是什么,系统都会在上一层生成一个FrameLayout节点,所以在布局根节点使用FrameLayout是多余的,但布局又不能没有根节点,所以,可以使用merge代替rameLayout,系统编译时不会为merge生成任何节点。merge的意思就是合并两个layout,可以大大减少多余节点的生成。

13、切换默认输入法(调用系统的输入法切换组件,会显示一个输入法列表供用户选择)
    try {
        ((InputMethodManager) context.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE))
                .showInputMethodPicker();
    } catch (Exception e) {
        Toast.makeText(context, R.string.changeInputMethodError,
                Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

14、显示或隐藏输入法软键盘
    InputMethodManager imm =
        (InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive()) {
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,InputMethodManager.HIDE_NOT_ALWAYS);
    }
(因为我是在Fragment中用的,所以代码中的mainActivity是getActivity()返回的对象)

15、隐藏输入法软键盘
    InputMethodManager inputMethodManager = (InputMethodManager) mainActivity
            .getSystemService(mainActivity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(mainActivity
            .getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
(因为我是在Fragment中用的,所以代码中的mainActivity是getActivity()返回的对象)

16、判断字符串是否是数字、汉字、英文字母
    public boolean isNum(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        }
        return false;
    }

    public boolean isZh(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        }
        return false;
    }

    public boolean isEn(String str) {
        if (str == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[a-zA-Z]*");
        Matcher isNum = pattern.matcher(str);
        if (isNum.matches()) {
            return true;
        }
        return false;
    }

17、创建一个是否退出程序的对话框
    @SuppressLint("HandlerLeak")
    protected void exitDialog() {
        AlertDialog.Builder builder = new Builder(this);
        builder.setMessage(getString(R.string.quitMsg));
        builder.setTitle(getString(R.string.quitTittle));
        builder.setPositiveButton(getString(R.string.sureQuit),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 点击确定,退出程序
                        finish();
                        System.exit(0);
                    }
                });
        builder.setNegativeButton(getString(R.string.cancleQuit),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 点击取消,什么也不做
                    }
                });
        builder.create().show();
    }

18、应用的私有文件创建和读取(用不到存储器的读写权限)
写入或创建:
    FileOutputStream fos;
    try {
        fos = mainActivity.openFileOutput(LoginFragment.LOGIN_INFO_FILE_NAME,
                    Context.MODE_PRIVATE);
        String writeStr = "write data";
        fos.write(writeStr.getBytes("UTF-8"));
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
读取:
    FileInputStream fis = null;
    byte[] buffer = new byte[1024];
    String strRead = null;
    try {
        fis = mainActivity.openFileInput(LOGIN_INFO_FILE_NAME);
        fis.read(buffer);
        fis.close();
        strRead = EncodingUtils.getString(buffer, "UTF-8");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

19、延时运行
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            // 此处填写需要延时运行的方法语句
        }
    }, 2000); // 延时2000毫秒

20、SlidingMenu 使用方法
    private SlidingMenu slidingMenu = null;
    // b 为 false 时禁止
    private void setSlidingMenu(Boolean b) {
        slidingMenu = getSlidingMenu();
        // 设置主界面和侧边栏之间的分割线
        slidingMenu.setShadowDrawable(R.drawable.drawer_shadow);
        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        // 设置侧边栏的宽度为屏幕的三分之二
        slidingMenu.setBehindWidth(getWindowManager().getDefaultDisplay().getWidth() / 3 * 2);
        // 设置操作时显示的渐变效果的程度(0-1f)
        slidingMenu.setFadeDegree(0.35f);
        if (b) {
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        } else {
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        }
    }

21、横竖屏切换时
    在AndroidManifest.xml文件中给activity标签添加属性:
    android:configChanges="orientation|keyboardHidden"
    复写方法:
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.i("--Main--", "onConfigurationChanged");
        if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
            // 当前屏幕为横屏
        }else{
            // 当前屏幕为竖屏
        }
        // 只要横竖屏状态发生改变,就重新设置侧边栏的宽度
        slidingMenu.setBehindWidth(getWindowManager().getDefaultDisplay().getWidth() / 3 * 2);
    }

22、在程序启动界面显示时禁止使用返回键和菜单键,进入主界面后启用,并可通过菜单键打开侧边栏
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!CONTENT_PAGE_STATE) {
                return false;
            }
            if (!slidingMenu.isMenuShowing()) {
                // exitBy2Click();
                exitDialog();
            }
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
            if (!CONTENT_PAGE_STATE) {
                return false;
            }
            Log.i(TAG, getString(R.string.openLeftMenu));
            toggle();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

23、双击back键退出
    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true;
            Toast.makeText(this, getString(R.string.exitInfo),
                    Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 1000);
        } else {
            finish();
            System.exit(0); // 加上可清理资源
        }
    }

 

posted @ 2014-03-29 17:02  挽风阁  阅读(268)  评论(0编辑  收藏  举报