Android

Android开发中,那些相见恨晚的方法、类和接口以及一些不可不

2017-10-11  本文已影响36人  爱码士
图标资源.png

这里收集了大家常用的一些Android代码,持续更新中,内容来自自己的平时积累和网络上看到的文章,部分原文地址在最下方。如有错误欢迎指正,如有侵权,请联系我删除。里面可能会有重复内容,请忽略或者提醒我删除。<br /><br />

createVideoThumbnail(String filePath, int kind)
extractThumbnail(Bitmap source, int width, int height)
//方法1: 
//无title   
requestWindowFeature(Window.FEATURE_NO_TITLE);    
getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN,WindowManager.LayoutParams. FLAG_FULLSCREEN);   
//必须在setContentView()之前调用
setContentView(R.layout.main);  
//方法2:
<activity android:name="." 
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" //全屏主题
    android:label="@string/app_name" />

再在 TabLayout 的布局文件里设置 app:tabTextAppearance="@style/CustomTabLayoutTextAppearance" 即可。

public static void printMap(Map mp) {
    for (Map.Entry m : mp.entrySet()) {
            System.out.println(m.getKey() + ":" + m.getValue());
        }
}
public static int randInt(int min, int max) {
    Random rand = new Random();
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}
  1. 插好数据线,拨号界面 输入 ##2846579## 进入工程模式
  2. projectmenu→3后台设置→4USB端口配置→Balong调试模式,点确定
  3. 不要拔线,退出工程模式,直接重启手机,电脑中显示可移动磁盘(若仍未出现,重复步骤1、2)
  4. 这个是关闭USB调试的情况下电脑中使用手机的可移动磁盘的方法,使用后下拉菜单中usb选项也回来了。
<android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:stackFromEnd="true"
        app:layoutManager="LinearLayoutManager"/>
<declare-styleable name="RecyclerView">
        <attr name="layoutManager" format="string"/>
        <attr name="android:orientation"/>
        <attr name="spanCount" format="integer"/>
        <attr name="reverseLayout" format="boolean"/>
        <attr name="stackFromEnd" format="boolean"/>
</declare-styleable>
public static Properties getProperties(Context context, AttributeSet attrs,
                int defStyleAttr, int defStyleRes) {
            Properties properties = new Properties();
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView,
                    defStyleAttr, defStyleRes);
            properties.orientation = a.getInt(R.styleable.RecyclerView_android_orientation,
                    VERTICAL);
            properties.spanCount = a.getInt(R.styleable.RecyclerView_spanCount, 1);
            properties.reverseLayout = a.getBoolean(R.styleable.RecyclerView_reverseLayout, false);
            properties.stackFromEnd = a.getBoolean(R.styleable.RecyclerView_stackFromEnd, false);
            a.recycle();
            return properties;
        }
public static Bitmap blurBitmap(Context context, Bitmap src, int radius) {
        Bitmap dest = src.copy(src.getConfig(), true);
        RenderScript rs = RenderScript.create(context);
        Allocation allocation = Allocation.createFromBitmap(rs, src);
        Type t = allocation.getType();
        Allocation blurredAllocation = Allocation.createTyped(rs, t);
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        blurScript.setRadius(radius);
        blurScript.setInput(allocation);
        blurScript.forEach(blurredAllocation);
        blurredAllocation.copyTo(dest);
        allocation.destroy();
        blurredAllocation.destroy();
        blurScript.destroy();
        t.destroy();
        rs.destroy();
        return dest;
    }
public static Bitmap createBitmap(View v){
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
        v.setDrawingCacheEnabled(false);
        return bitmap;
    }
public static Bitmap createBitmap(ScrollView v){
        int width = 0 ,height = 0;
        for (int i = 0; i < v.getChildCount(); i++){
            width += v.getChildAt(i).getWidth();
            height += v.getChildAt(i).getHeight();
        }
        Bitmap bitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:background="#FF00FF"
    tools:visibility="visible"
    tools:text="这段话只在预览时能看到,运行以后就看不到了" />
android {
    defaultConfig {
    ...
            jackOptions {
                enabled true
            }
        }
   ...
    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }
}
git rm -r --cached .
git add .
git commit -m 'update .gitignore'
<style name="Theme.YourApp" parent="android:style/Theme.Light">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
</style>

这样,控件的宽高默认都是wrap_content样式啦。

<style name="Fill">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">fill_parent</item>
</style>
<style name="Fill.Height" >
    <item name="android:orientation">vertical</item>
</style>
android {
    buildTypes {
        debug {
            applicationIdSuffix '.debug'
            versionNameSuffix '-DEBUG'
        }
        release {
            //...
        }
    }
}
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
    recyclerView.setLayoutManager(linearLayoutManager);
    LinearSnapHelper snapHelper = new LinearSnapHelper();
    snapHelper.attachToRecyclerView(recyclerView);
ArrayMap<K,V> in place of HashMap<K,V> 
ArraySet<K,V> in place of HashSet<K,V> 
SparseArray<V> in place of HashMap<Integer,V> 
SparseBooleanArray in place of HashMap<Integer,Boolean> 
SparseIntArray in place of HashMap<Integer,Integer>  
SparseLongArray in place of HashMap<Integer,Long>  
LongSparseArray<V> in place of HashMap<Long,V>
    return UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
<item name="android:windowBackground">@null</item>
 Configuration configuration = getResources().getConfiguration();
  configuration.fontScale = (float) 1; 
  //0.85 小, 1 标准大小, 1.15 大,1.3 超大 ,1.45 特大 
  DisplayMetrics metrics = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(metrics); 
  metrics.scaledDensity = configuration.fontScale * metrics.density;
  getBaseContext().getResources().updateConfiguration(configuration, metrics); 
  //(ps:dialog popupwindow 除外,这两种需要在控件中重新设置fontScale)
public class Colors {
    @IntDef({RED, GREEN, YELLOW})
    //声明必要的int常量,使用@IntDef修饰LightColors,参数设置为待枚举的集合
    @Retention(RetentionPolicy.SOURCE)
    //使用@Retention(RetentionPolicy.SOURCE)指定注解仅存在与源码中,不加入到class文件中
    public @interface LightColors{}
    //声明一个注解为LightColors
    public static final int RED = 0;
    public static final int GREEN = 1;
    public static final int YELLOW = 2;
}
//用法
private void setColor(@Colors.LightColors int color) {
        Log.d("MainActivity", "setColor color=" + color);
}
//调用的该方法的时候
setColor(Colors.GREEN);
Path path = new Path();
path.cubicTo(0.2f, 0f, 0.1f, 1f, 0.5f, 1f);
path.lineTo(1f, 1f);
ObjectAnimator animator = ObjectAnimator.ofFloat(view, View.TRANSLATION_X, 500);
animator.setInterpolator(PathInterpolatorCompat.create(path));
animator.start();
public static boolean isNetWorkAvailable(final Context context) {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process pingProcess = runtime.exec("/system/bin/ping -c 1 www.baidu.com");
            int exitCode = pingProcess.waitFor(); //0 代表连通,2代表不通
            return (exitCode == 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
@Override
  public void onBackPressed() {
    moveTaskToBack(false);
  }
try {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    format.setLenient(false);
    //要转换字符串 str_test  自定义的格式为 yyyy-mm-dd,可以改成你需要的格式
    String str_test ="2011-04-24";
    Timestamp ts = new Timestamp(format.parse(str_test).getTime());
    System.out.println(ts.toString());
} catch (ParseException e) {
e.printStackTrace();
}
上一篇下一篇

猜你喜欢

热点阅读