How to check visibility of software keyboard in Android

2015年7月17日 09:25

In AndroidManifest.xml

        <activity
            android:name=".activity.LoginActivity"
            android:label="@string/app_name" 
            android:windowSoftInputMode="adjustResize"
            >
        </activity>

1.Use onMeasure() method

This method have problem on Sumsung S4. The onMeasure() Method will run three times after the keyboard appear. But only the second time run result is right, the last run result is : the size of the window no changed. So the onShow() method will not run.

//define custom layout
//LoginLayout.java
package com.pxdl.carsystem.layout;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RelativeLayout;

public class LoginLayout extends RelativeLayout {
    public LoginLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LoginLayout(Context context) {
        super(context);
    }

    private OnSoftKeyboardListener onSoftKeyboardListener;

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        if (onSoftKeyboardListener != null) {
            final int newSpec = MeasureSpec.getSize(heightMeasureSpec); 
            final int oldSpec = getMeasuredHeight();
            if (oldSpec > newSpec){
                onSoftKeyboardListener.onShown();
            } else {
                onSoftKeyboardListener.onHidden();
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public final void setOnSoftKeyboardListener(final OnSoftKeyboardListener listener) {
        this.onSoftKeyboardListener = listener;
    }

    public interface OnSoftKeyboardListener {
        public void onShown();
        public void onHidden();
    }
}

//activity.java
ly_main.setOnSoftKeyboardListener(new OnSoftKeyboardListener() {
        @Override
        public void onShown() {
            hideImgIcon();
        }
        @Override
        public void onHidden() {
            showImgIcon();
        }
    });

2.Simpler method Use OnGlobalLayoutListener

//activity.java
ly_main.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = ly_main.getRootView().getHeight() - ly_main.getHeight();
                if (heightDiff > 200) { // if more than 200 pixels, its probably a keyboard...
                    hideImgIcon();
                }else{
                    showImgIcon();
                }
             }
        });

继续阅读 »

判断手机有没有被root

2013年5月31日 16:53

原文链接

http://code.google.com/p/roottools/

if (RootTools.isRootAvailable()) {
    // your app has been granted root access
}
if (RootTools.isAccessGiven()) {
    // your app has been granted root access
}

继续阅读 »