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

注意:本文原創(chuàng),轉(zhuǎn)載請注明出處。歡迎關(guān)注我的 簡書
** 本篇文章是記錄Android開發(fā)中需要總結(jié)記錄的代碼片段,以便后面隨時查看。*

EditText點擊時不彈出軟鍵盤

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

防止EditText獲取默認焦點

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

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

判斷應(yīng)用是否已經(jīng)啟動

/**
 * 判斷應(yīng)用是否已經(jīng)啟動
 * @param context 一個context
 * @param packageName 要判斷應(yīng)用的包名
 * @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

如果要給條目中間添加間距,怎么實現(xiàn)呢?當然也很簡單,比如添加一個高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方法沒有繪制任何東西,那么性能也就幾乎沒有影響。
實現(xiàn)代碼:

<?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 中的轉(zhuǎn)場動畫及兼容處理

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

關(guān)于android中ratingbar星數(shù)不受控制的問題

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
出現(xiàn)錯誤的原因是:Androidstudio嚴格審查png圖片,就是png沒有達到Androidstudio的要求

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

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

Android WebView加載某些URL,點擊button或者其他鏈接無反應(yīng)

因為URL中使用了localStorage,但是默認WebView沒有打開localStorage導(dǎo)致的。解決方案:

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); 

轉(zhuǎn)自: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);

轉(zhuǎn)自 http://www.lxweimin.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èi)存中其實只有n個View,當我們在滾動時,第(n+1)個View復(fù)用第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

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

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






















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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,619評論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,155評論 3 425
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,635評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,539評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,255評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,646評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,655評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,838評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,399評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,146評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,338評論 1 372
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,893評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,565評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,983評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,257評論 1 292
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,059評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,296評論 2 376

推薦閱讀更多精彩內(nèi)容