Android開發(fā)代碼片段(持續(xù)更新)

注意:本文原創(chuàng)竹椒,轉載請注明出處嘉赎。歡迎關注我的 簡書
** 本篇文章是記錄Android開發(fā)中需要總結記錄的代碼片段亩冬,以便后面隨時查看艘希。*

EditText點擊時不彈出軟鍵盤

EditText mEditText = (EditText) findViewById(R.id.edit_text);
mEditText.setInputType(InputType.TYPE_NULL);

防止EditText獲取默認焦點

在開發(fā)的過程中,由于頁面布局最下面有個EditText硅急,導致Activity顯示的時候覆享,總是自動滾動到下面。后來發(fā)現是由于EditText默認獲取到了焦點導致的营袜。解決的方法就是在Activity的頁面上方布局(任意一個都可以)加上以下代碼撒顿,即可解決。

android:focusable="true"
android:focusableInTouchMode="true"

判斷應用是否已經啟動

/**
 * 判斷應用是否已經啟動
 * @param context 一個context
 * @param packageName 要判斷應用的包名
 * @return boolean
 */
public static boolean isAppAlive(Context context, String packageName){
    ActivityManager activityManager =
            (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> processInfos
            = activityManager.getRunningAppProcesses();
    for(int i = 0; i < processInfos.size(); i++){
        if(processInfos.get(i).processName.equals(packageName)){
            Log.i("NotificationLaunch",
                    String.format("the %s is running, isAppAlive return true", packageName));
            return true;
        }
    }
    Log.i("NotificationLaunch",
            String.format("the %s is not running, isAppAlive return false", packageName));
    return false;
}

巧用TextView的drawableLeft和drawableRight

注意:這個小節(jié)摘自唯鹿博客荚板。

Paste_Image.png
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:drawableLeft="@drawable/icon_1"
        android:drawableRight="@drawable/icon_4"
        android:drawablePadding="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:textSize="16sp"
        android:text="我的卡券"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

</LinearLayout>

兔子哥備注:如果想要讓“我的卡券”這個文字居中顯示凤壁,只需要把
android:gravity="center_vertical"改為android:gravity="center"

Space控件

注意:這個小節(jié)摘自唯鹿博客吩屹。

Paste_Image.png

如果要給條目中間添加間距,怎么實現呢拧抖?當然也很簡單煤搜,比如添加一個高10dp的View,或者使用android:layout_marginTop="10dp"等方法唧席。但是增加View違背了我們的初衷擦盾,并且影響性能。使用過多的margin其實會影響代碼的可讀性淌哟。

這時你就可以使用Space迹卢,他是一個輕量級的。我們可以看下源碼:

/**
 * Space is a lightweight View subclass that may be used to create gaps between components
 * in general purpose layouts.
 */
public final class Space extends View {
    /**
     * {@inheritDoc}
     */
    public Space(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        if (getVisibility() == VISIBLE) {
            setVisibility(INVISIBLE);
        }
    }

    /**
     * {@inheritDoc}
     */
    public Space(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    /**
     * {@inheritDoc}
     */
    public Space(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /**
     * {@inheritDoc}
     */
    public Space(Context context) {
        //noinspection NullableProblems
        this(context, null);
    }

    /**
     * Draw nothing.
     *
     * @param canvas an unused parameter.
     */
    @Override
    public void draw(Canvas canvas) {
    }

    /**
     * Compare to: {@link View#getDefaultSize(int, int)}
     * If mode is AT_MOST, return the child size instead of the parent size
     * (unless it is too big).
     */
    private static int getDefaultSize2(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
            case MeasureSpec.UNSPECIFIED:
                result = size;
                break;
            case MeasureSpec.AT_MOST:
                result = Math.min(size, specSize);
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
        }
        return result;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(
                getDefaultSize2(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize2(getSuggestedMinimumHeight(), heightMeasureSpec));
    }
}

可以看到在draw方法沒有繪制任何東西徒仓,那么性能也就幾乎沒有影響腐碱。
實現代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:divider="@drawable/divider"
    android:showDividers="middle|beginning|end">

    <TextView
        android:drawableLeft="@drawable/icon_1"
        android:drawableRight="@drawable/icon_4"
        android:drawablePadding="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:textSize="16sp"
        android:text="我的卡券"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <TextView
        android:drawableLeft="@drawable/icon_2"
        android:drawableRight="@drawable/icon_4"
        android:drawablePadding="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:textSize="16sp"
        android:text="地址管理"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <Space
        android:layout_width="match_parent"
        android:layout_height="15dp"/>

    <TextView
        android:drawableLeft="@drawable/icon_3"
        android:drawableRight="@drawable/icon_4"
        android:drawablePadding="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:textSize="16sp"
        android:text="檢查更新"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

</LinearLayout>

讓App無法使用截圖

getWindow().addFlags(WindowManager.LayoutParams. FLAG_SECURE);

這個FLAG的定義如下(看注釋就知道這個標志防止使用截圖):

/** Window flag: treat the content of the window as secure, preventing
 * it from appearing in screenshots or from being viewed on non-secure
 * displays.
 *
 * <p>See {@link android.view.Display#FLAG_SECURE} for more details about
 * secure surfaces and secure displays.
 */
public static final int FLAG_SECURE             = 0x00002000;

Android 中的轉場動畫及兼容處理

http://blog.csdn.net/wl9739/article/details/52833668

關于android中ratingbar星數不受控制的問題

http://blog.csdn.net/kkkding/article/details/8968438

Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:錯誤

http://blog.csdn.net/u012737144/article/details/53782164
出現錯誤的原因是:Androidstudio嚴格審查png圖片,就是png沒有達到Androidstudio的要求

當我們ScrollView的最上層的Layout里面多多個孩子的時候蓬衡,當下面一個孩子是RecyclerView或者ListView的時候喻杈,往往會自動滑動到ListView或者RecyclerView 的第一個item,導致進入界面的時候會導致RecyclerView 上面的 View被滑動到界面之外

http://blog.csdn.net/gdutxiaoxu/article/details/52939127

Android WebView加載某些URL狰晚,點擊button或者其他鏈接無反應

因為URL中使用了localStorage筒饰,但是默認WebView沒有打開localStorage導致的。解決方案:

mWebView.getSettings().setDomStorageEnabled(true);   
mWebView.getSettings().setAppCacheMaxSize(1024*1024*8);  
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();  
mWebView.getSettings().setAppCachePath(appCachePath);  
mWebView.getSettings().setAllowFileAccess(true);  
mWebView.getSettings().setAppCacheEnabled(true); 

轉自:http://www.cnblogs.com/yuzhongwusan/p/4211681.html

修改AlertDialog按鈕的顏色

修改前


Paste_Image.png

修改后

Paste_Image.png
   <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <!--自定義AlertDialog-->
        <item name="alertDialogTheme">@style/Theme.AppCompat.Light.Dialog.Alert.Self</item>
    </style>
    <style name="Theme.AppCompat.Light.Dialog.Alert.Self"
           parent="@style/Theme.AppCompat.Light.Dialog.Alert">
        <!--修改AlertDialog按鈕的顏色-->
        <item name="colorAccent">#3F51B5</item>
    </style>
</resources>

或者:

// 需要在dialog show或者create 之后才可以更改
dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(neededColor); 
dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(neededColor);

轉自 http://www.reibang.com/p/fb671e11e455

Android中hasFocus()和isFocused()的區(qū)別

分析一:

hasFocus() is different from isFocused(). hasFocus() == true means that the View or one of its descendants is focused. If you look closely, there's a chain of hasFocused Views till you reach the View that isFocused.

分析二:

Sometimes views in Android are grouped together, and if one of the views in that group has focus, the hasFocus() method will return true, but only when the specific view you are mentioning in code is focused will isFocused() equal true.

來源:https://stackoverflow.com/questions/33022310/what-is-the-difference-between-hasfocus-and-isfocused-in-android

Android中GridView壁晒、ListView的getChildAt方法認識誤區(qū)

一開始以為傳入一個絕對的position(就是adapter的第幾個item)就可以返回該position的View瓷们。但是GridView和ListView對View采用回收機制,簡單的說明一下就是:如果屏幕最多可以顯示n個子View秒咐,那么內存中其實只有n個View谬晕,當我們在滾動時,第(n+1)個View復用第1個View携取,依次類推攒钳。
所以在GridView和ListView中,getChildAt ( int position ) 方法中position指的是當前可見區(qū)域的第幾個元素雷滋。

** 如果你要獲得GridView的第n個View不撑,那么position就是n減去第一個可見View的位置**

View view = getChildAt (n - getFirstVisiblePosition());

來源:http://blog.csdn.net/peakerli/article/details/37658649

十六進制顏色,需要加透明度方法

拿到十六進制顏色晤斩,需要加透明度焕檬,百度有很多 別人整理的。我隨便粘貼一個:






















嗯澳泵,網上很多实愚,這個我覺得還是比較正規(guī)的,放在0x(#)后面就行 比如 #FFFFFF 45%透明,就是#73FFFFFF

來源:http://blog.csdn.net/qq_31332467/article/details/74838617

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末腊敲,一起剝皮案震驚了整個濱河市击喂,隨后出現的幾起案子,更是在濱河造成了極大的恐慌兔仰,老刑警劉巖茫负,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蕉鸳,死亡現場離奇詭異乎赴,居然都是意外死亡,警方通過查閱死者的電腦和手機潮尝,發(fā)現死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進店門榕吼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人勉失,你說我怎么就攤上這事羹蚣。” “怎么了乱凿?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵顽素,是天一觀的道長。 經常有香客問我徒蟆,道長胁出,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任段审,我火速辦了婚禮全蝶,結果婚禮上,老公的妹妹穿的比我還像新娘寺枉。我一直安慰自己抑淫,他們只是感情好,可當我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布姥闪。 她就那樣靜靜地躺著始苇,像睡著了一般。 火紅的嫁衣襯著肌膚如雪筐喳。 梳的紋絲不亂的頭發(fā)上催式,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天,我揣著相機與錄音疏唾,去河邊找鬼蓄氧。 笑死,一個胖子當著我的面吹牛槐脏,可吹牛的內容都是我干的喉童。 我是一名探鬼主播,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼堂氯!你這毒婦竟也來了蔑担?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤咽白,失蹤者是張志新(化名)和其女友劉穎啤握,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體晶框,經...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡排抬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了授段。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蹲蒲。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖侵贵,靈堂內的尸體忽然破棺而出届搁,到底是詐尸還是另有隱情,我是刑警寧澤窍育,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布卡睦,位于F島的核電站,受9級特大地震影響漱抓,放射性物質發(fā)生泄漏表锻。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一辽旋、第九天 我趴在偏房一處隱蔽的房頂上張望浩嫌。 院中可真熱鬧,春花似錦补胚、人聲如沸码耐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽骚腥。三九已至,卻和暖如春瓶逃,著一層夾襖步出監(jiān)牢的瞬間束铭,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工厢绝, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留契沫,地道東北人。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓昔汉,卻偏偏與公主長得像懈万,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內容