2015年11月25日 星期三

[Exception] The specified child already has a parent. You must call removeView() on the child's parent first.

Reference:
http://www.cnblogs.com/over140/archive/2013/06/06/3121354.html

Pre-condition:
Activity + Fragment

Solution:
View v = inflater.inflate(R.layout.preference_fragment, container, false);


Set the focus and display the keyboard on EditText

Reference:

http://stackoverflow.com/questions/8991522/how-can-i-set-the-focus-and-display-the-keyboard-on-my-edittext-programmatic

Code snippet:

EditText editText = (EditText) findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)                     getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

2015年11月13日 星期五

Get screen shot bitmap

Code snippet:

public Bitmap getScreenShot(int x,int y,int width,int height){
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        final Bitmap screenShot = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);
        final Bitmap cropBitmap = Bitmap.createBitmap(screenShot,x,y,width,height);
        return cropBitmap.copy(cropBitmap.getConfig(),true);
}

2015年11月11日 星期三

Check if Google Play Service is available

Reference:

http://stackoverflow.com/questions/18737632/how-to-check-google-play-services-version
http://stackoverflow.com/questions/28479849/when-does-isgoogleplayservicesavailable-return-service-version-update-required
http://stackoverflow.com/questions/25989727/isgoogleplayservicesavailable-always-returns-2
http://www.4byte.cn/question/135275/googlemap-v2-crash-if-first-use-android.html

Code snippet:

public static void checkGooglePlayServiceAvailability(Activity activity){
        Log.d(TAG,"sdk gms versionCode: " + GooglePlayServicesUtil.GOOGLE_PLAY_SERVICES_VERSION_CODE);
        try{
            int deviceGmsVersion = activity.getPackageManager().getPackageInfo("com.google.android.gms",0).versionCode;
            Log.d(TAG,"" + "device gms versionCode: " + deviceGmsVersion);
        } catch(Exception e){
            e.printStackTrace();
        }

        int statusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
        Log.e(TAG,"statuscode: " + statusCode);
        Log.e(TAG,"error string: " + GooglePlayServicesUtil.getErrorString(statusCode));

        if(statusCode != ConnectionResult.SUCCESS){
            if(GooglePlayServicesUtil.isUserRecoverableError(statusCode)){
                Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(statusCode, activity, 0);
                // If Google Play services can provide an error dialog
                if (errorDialog != null) {
                    errorDialog.show();
                }
            }
        }
    }

2015年11月10日 星期二

Handle back key event

Reference:

http://stackoverflow.com/questions/5312334/how-to-handle-back-button-in-activity

Code snippet:

For API level 5

@Override
public void onBackPressed() {
    // your code.
}

For older then API 5 use this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

2015年11月9日 星期一

Get the view's height when the views are not built in onCreate(), onStart(), or onResume()

Reference:
http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve-dimensions-of-a-view-getheight-and-getwidth-always-r/4406090#4406090
http://stackoverflow.com/questions/8170915/getheight-returns-0-for-all-android-ui-objects
http://www.eoeandroid.com/thread-240677-1-1.html?_dsign=f73765c1

Code snippet:
private ViewTreeObserver mViewTreeObserver;
private TextView mTextView;
protected void onCreate(Bundle savedInstanceState) {
    .........
    mTextView = (TextView) findViewById(R.id.my_text_view);
    mViewTreeObserver = mTextView.getViewTreeObserver();
    mViewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {                      
                        int height = mTextView.getHeight();
                        if(!mViewTreeObserver.isAlive()){
                            mViewTreeObserver = mNewTrackingRelativeLayout.getViewTreeObserver();
                        }
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            mViewTreeObserver.removeOnGlobalLayoutListener(this);
                        } else {
                            mViewTreeObserver.removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    .........
}


2015年11月6日 星期五

Add search button on keyboard and close the keyboard when click the search button

Reference:
http://stackoverflow.com/questions/3205339/android-how-to-make-keyboard-enter-button-say-search-and-handle-its-click
http://stackoverflow.com/questions/23528644/edittext-ignores-the-imeactionlabel
http://stackoverflow.com/questions/3400028/close-virtual-keyboard-on-button-press
http://stackoverflow.com/questions/13593069/androidhide-keyboard-after-button-click

Code snippet:
layout.xml

<EditText android:imeOptions="actionSearch"
    android:inputType="text"/>

class.java

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();

            // close the keyboard
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                      InputMethodManager.RESULT_UNCHANGED_SHOWN);
            return true;
        }
        return false;
    }
});

2015年11月5日 星期四

How to solve "adb server is out of date.killing" problem

Reference:
http://yeeapps.com/11/news_detial.php?news_id=adb%20server%20is%20out%20of%20date.killing%E7%9A%84%E8%A7%A3%E6%B1%BA%E6%96%B9%E6%B3%95

Step:
1. 在cmd中執行adb nodaemon server,查看adb的埠號是多少,一般情況下是5037
2. 再執行netstat -ano | findstr "5037",找出佔據埠號5037的程序,並記錄其 PID
3. 到工作管理員中,將同一個 PID的程序刪除

2015年11月4日 星期三

Changing layout height programmatically

Reference:

http://www.cnblogs.com/wanqieddy/p/4040601.html

Code snippet:

layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/my_relative_layout_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        ................


class.java:

RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.my_relative_layout_id);
mRelativeLayout.setLayoutParams(new LinearLayout.LayoutParams(200,600));


Note:

setLayoutParams裡的參數型態不是要改變高度的 layout型態,而是要和外面一層layout的型態相同(如上面紅字所標註),否則會出現 ClassCastException
以上面的範例來說,要改變高度的 layout型態是 RelativeLayout,如果 setLayoutParams裡面帶入的參數型態為 RelativeLayout.LayoutParams,就會出現下面的 exception

java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

因為要改變高度的 layout,外面一層的 layout型態為 LinearLayout,所以setLayoutParams裡面帶入的參數型態要是 LinearLayout.LayoutParams