Android开发代码片段(持续更新)

注意:本文原创,转载请注明出处。欢迎关注我的 。
** 本篇文章是记录Android开发中需要总结记录的代码片段,以便后面随时查看。*

EditText点击时不弹出软键盘

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

防止EditText获取默认焦点

在开发的过程中,由于页面布局最下面有个EditText,导致Activity显示的时候,总是自动滚动到下面。后来发现是由于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 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

注意:这个小节摘自唯鹿 的博客。

Android开发代码片段(持续更新)_第1张图片
Paste_Image.png



    



兔子哥备注:如果想要让“我的卡券”这个文字居中显示,只需要把
android:gravity="center_vertical"改为android:gravity="center"

Space控件

注意:这个小节摘自唯鹿 的博客。

Android开发代码片段(持续更新)_第2张图片
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方法没有绘制任何东西,那么性能也就几乎没有影响。
实现代码:




    

    

    

    


让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.
 *
 * 

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按钮的颜色

修改前


Android开发代码片段(持续更新)_第3张图片
Paste_Image.png

修改后

Android开发代码片段(持续更新)_第4张图片
Paste_Image.png
   
    


或者:

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

转自 http://www.jianshu.com/p/fb671e11e455

Android中hasFocus()和isFocused()的区别

分析一:

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方法认识误区

一开始以为传入一个绝对的position(就是adapter的第几个item)就可以返回该position的View。但是GridView和ListView对View采用回收机制,简单的说明一下就是:如果屏幕最多可以显示n个子View,那么内存中其实只有n个View,当我们在滚动时,第(n+1)个View复用第1个View,依次类推。
所以在GridView和ListView中,getChildAt ( int position ) 方法中position指的是当前可见区域的第几个元素。

** 如果你要获得GridView的第n个View,那么position就是n减去第一个可见View的位置**

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

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

十六进制颜色,需要加透明度方法

拿到十六进制颜色,需要加透明度,百度有很多 别人整理的。我随便粘贴一个:






















嗯,网上很多,这个我觉得还是比较正规的,放在0x(#)后面就行 比如 #FFFFFF 45%透明,就是#73FFFFFF

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

你可能感兴趣的:(Android开发代码片段(持续更新))