Android 零碎知识点汇总

一些零碎的知识点,似乎不足以开篇,汇总记录在此。持续更新。

控件部分

一、TextView 

// 添加滚动条,实现滚动

<TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="100dip"
        android:scrollbars="vertical"
        android:text="@string/test_data_50" />
txt = (TextView) findViewById(R.id.txt);
txt.setMovementMethod(ScrollingMovementMethod.getInstance());

// 添加图片

在xml中设置

<TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="100dip"
        android:drawableLeft="@drawable/txt_left"
        android:drawableRight="@drawable/txt_right"
        android:drawableTop="@drawable/txt_top"
        android:drawableBottom="@drawable/txt_bottom"
        android:text="@string/test_data_50" />

在代码中设置

textLeft.setCompoundDrawablesWithIntrinsicBounds(R.drawable.img, 0, 0, 0);
textLeft.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);

// 添加删除线

txt.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

// 添加下划线

textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
textView.getPaint().setAntiAlias(true);//抗锯齿

// 转换html代码

textview.setText(Html.fromHtml(getString(R.string.test)));

// 设置最大宽度

xml需要设置宽度为wrap_content

代码设置

// 修改名字最大宽度
if (maxWidthName <= 0) {
     DisplayMetrics dm = new DisplayMetrics();
     ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
     int width = dm.widthPixels;
     DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
     maxWidthName = width - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 180, metrics);
}
viewHolder.tvMeName.setMaxWidth(maxWidthName);

// 设置图片大小

tv_titlebar_right?.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.gift_explanation, 0)

ContextCompat.getDrawable(applicationContext, R.mipmap.gift_explanation).let {
    it?.setBounds(0, 0, 14.dp, 14.dp) // 距左边距离,距上边距离,长,宽
    tv_titlebar_right?.setCompoundDrawablesWithIntrinsicBounds(null, null, it, null)
}

*、ImageView

 <ImageView
    android:id="@+id/iv_back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_marginStart="14dp"
    android:src="@mipmap/menu_back"
    app:tint="@color/white" />


// 代码设置 tint

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    iv_back?.imageTintList = ColorStateList.valueOf(
       AppUtils.getColor(applicationContext,R.color.white)
    )
}

// 从mp4视频截取一张图做封面
var temp = "https://static.yximgs.com/udata/pkg/fe/kwai_video.a7616d99.mp4"
Glide.with(context)
     .setDefaultRequestOptions(
          RequestOptions()
              .frame(1000000) // 第一秒
              .centerCrop()
              .error(R.mipmap.default_loading)
              .placeholder(R.mipmap.default_error)
          )
     .load(temp)
     .into(holder.getView(R.id.iv_image))           

二、EditText

// 默认隐藏输入法

方法一:在xml文件中设置,

使用 android:focusable="true" android:focusableInTouchMode="true" 设置在EditText父控件中

<LinearLayout
        android:id="@+id/ll_test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:focusableInTouchMode="true" />


方法二:在代码中设置

InputMethodManager inputManager = (InputMethodManager) edtText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(edtText.getWindowToken(), 0);

// 取消焦点

edtText.clearFocus();

// 回车换行

edtText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    int index = etActivityContent.getSelectionStart();//获取光标所在位置
                    Editable edit = edtText.getEditableText();//获取EditText的文字
                    if (index < 0 || index >= edit.length()){
                        edit.append("\n");
                    }else{
                        edit.insert(index,"\n"); //光标所在位置插入文字
                    }
                    return true;
                }

                return false;
            }
        });

三、LIstView 

// 设置列表项间隔

<ListView
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:divider="@color/line"
     android:dividerHeight="0.1dip"
     android:scrollbars="none" />

// 设置禁止滚动超出屏幕

android:overScrollMode="never"


// 设置默认选择某一项

// 设置选中第一项
listview.getChildAt(0).setSelected(true);
// 或者模拟点击第一项
listview.performItemClick(listview.getChildAt(0), 0, listAdapter.getItemId(0)); 

四、ScrollView

// 滚动到顶部

scroll.smoothScrollTo(0, 0);

五、GridView 

// 设置item的分割线

使用 horizontalSpacing 和 verticalSpacing

给GridView 和 item 设置不同的背景色

android:horizontalSpacing="1dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp"

六、HorizontalScrollView

//  滚动到指定位置

hsvTopWeek.scrollTo(100, 0);

七、DatePickerDialog

// 隐藏年
dateDialog.getDatePicker().findViewById(Resources.getSystem().getIdentifier("year", "id", "android")).setVisibility(View.GONE);

// 设置最高选择日期
dateDialog.getDatePicker().setMaxDate(DateUtils.getCurYearMaxLongMillis());
// 设置最低选择日期
dateDialog.getDatePicker().setMinDate(DateUtils.getCurYearMinLongMillis());

八、Button

// 模拟按钮点击, 也适用TextView等控件
btnTest.performClick();

九、ProgressBar 

// 水平进度条 自定义样式

<ProgressBar
            android:id="@+id/pb_poll"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="180dip"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/img_avatar"
            android:layout_marginLeft="10dip"
            android:layout_toRightOf="@+id/img_avatar"
            android:maxHeight="6dip"
            android:minHeight="6dip"
            android:progressDrawable="@drawable/progress_bar_vote" />


// progress_bar_vote.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!--背景-->
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="3dip" />

            <solid android:color="@color/gray_f3" />
        </shape>
    </item>
    <!--第二进度条-->
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="3dip" />

                <solid android:color="@color/txt_udou_home" />
            </shape>
        </clip>
    </item>
    <!--当前进度-->
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="3dip" />

                <solid android:color="@color/txt_udou_home" />
            </shape>
        </clip>
    </item>

</layer-list>

布局视图部分

一、显示一条分割线

<View
     android:layout_width="match_parent"
     android:layout_height="0.1dip"
     android:background="@color/line" />

二、为布局设置 selector 问题

为布局增加点击效果,注意要设置 android:clickable=“true” ,不然点击没有效果

android:clickable="true"
android:background="@drawable/layout_selector"

三、java 代码设置颜色

以textView设置字体颜色为例

// 使用系统自带的
text.setTextColor(Color.RED);

// 使用R.color资源
<color name="red">#ff0000</color>
text.setTextColor(getResources().getColor(R.color.red));

// 使用十六进制
text.setTextColor(Color.parseColor("#FF0000"));

// 使用 RGB
text.setTextColor(Color.rgb(250,0,0));

// 使用 ARGB
text.setTextColor(Color.argb(0,250,0,0));

// 使用 HEX
text.setTextColor(0xAARRGGBB);

final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
   text.setTextColor(ContextCompat.getColor(this, R.color.red));
} else {
   text.setTextColor(getResources().getColor(R.color.red));
}

四、颜色透明度

for (double i = 1; i >= 0; i -= 0.01) {
    i = Math.round(i * 100) / 100.0d;
    int alpha = (int) Math.round(i * 255);
    String hex = Integer.toHexString(alpha).toUpperCase();
    if (hex.length() == 1) hex = "0" + hex;
    int percent = (int) (i * 100);
    System.out.println(String.format("%d%% — %s", percent, hex));
}
100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00

参看这里

五、获取dimens值

int height = getResources().getDimensionPixelSize(R.dimen.viewpager_header_height);

六、View To Image,视图保存为图片

private Bitmap getBitmapFromView(View view) {
    // Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
    // Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    // Get the view's background
    Drawable bgDrawable =view.getBackground();
    if (bgDrawable!=null){
        // has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    }else {
        // does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    }
    // draw the view on the canvas
    view.draw(canvas);
    // return the bitmap
    return returnedBitmap;
}

private File getEmptyFile() {
    String timetemp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    String fileName = timetemp + "_";
    File fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    try {
        File file = File.createTempFile(fileName, ".jpg", fileDir);
        return file;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}


/**
     * 保存 view 为图片,存在相册
     *
     * @param view
     */
    public void saveViewToPhoto(View view) {
        Bitmap bitmap = getBitmapFromView(view);
        File file = getEmptyFile();
        if (bitmap != null && file != null) {
            try {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));

                //通知更新相册
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(DocumentFile.fromFile(file).getUri());
                getContext().sendBroadcast(intent);

                ToastUtil.showToast(getContext(), "已保存到相册");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

参看这里

七、国家/地区 语音缩写代码

国家/地区语言代码国家/地区语言代码
简体中文(中国)zh-cn繁体中文(台湾地区)zh-tw
繁体中文(香港)zh-hk英语(香港)en-hk
英语(美国)en-us英语(英国)en-gb
英语(全球)en-ww英语(加拿大)en-ca
英语(澳大利亚)en-au英语(爱尔兰)en-ie
英语(芬兰)en-fi芬兰语(芬兰)fi-fi
英语(丹麦)en-dk丹麦语(丹麦)da-dk
英语(以色列)en-il希伯来语(以色列)he-il
英语(南非)en-za英语(印度)en-in
英语(挪威)en-no英语(新加坡)en-sg
英语(新西兰)en-nz英语(印度尼西亚)en-id
英语(菲律宾)en-ph英语(泰国)en-th
英语(马来西亚)en-my英语(阿拉伯)en-xa
韩文(韩国)ko-kr日语(日本)ja-jp
荷兰语(荷兰)nl-nl荷兰语(比利时)nl-be
葡萄牙语(葡萄牙)pt-pt葡萄牙语(巴西)pt-br
法语(法国)fr-fr法语(卢森堡)fr-lu
法语(瑞士)fr-ch法语(比利时)fr-be
法语(加拿大)fr-ca西班牙语(拉丁美洲)es-la
西班牙语(西班牙)es-es西班牙语(阿根廷)es-ar
西班牙语(美国)es-us西班牙语(墨西哥)es-mx
西班牙语(哥伦比亚)es-co西班牙语(波多黎各)es-pr
德语(德国)de-de德语(奥地利)de-at
德语(瑞士)de-ch俄语(俄罗斯)ru-ru
意大利语(意大利)it-it希腊语(希腊)el-gr
挪威语(挪威)no-no匈牙利语(匈牙利)hu-hu
土耳其语(土耳其)tr-tr捷克语(捷克共和国)cs-cz
斯洛文尼亚语sl-sl波兰语(波兰)pl-pl
瑞典语(瑞典)sv-se西班牙语 (智利)es-cl

参看这里

八、创建桌面快捷方式

/**
     * 为程序创建桌面快捷方式
     * 需要权限
     * <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
     */
    private void addShortcut() {
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");

        //快捷方式的名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
        shortcut.putExtra("duplicate", false); //不允许重复创建
        //注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序
        ComponentName comp = new ComponentName(getPackageName(), "." + this.getLocalClassName());
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));

        //快捷方式的图标
        Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.mipmap.app_logo);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);

        sendBroadcast(shortcut);
    }

其它部分

一、判断SD卡存在

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
	// 有SD卡
}


二、String 转 android.R.资源id

// 以图片为例
int resId = getResources().getIdentifier("icon" , "drawable", getPackageName());
// 以字符串为例
getResourceId("text", "string", getPackageName());


三、Intent传递List 、Map参数

可以使用 Intent.putExtra(String, Serializable) 传递

因为无论是 List 还是 HashMap,实际上都有实现了 Serializable 接口,Map 不在此列,需要时转成 HashMap 即可

以HashMap<String, String> 为例

HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("key", "value");
Intent intent = new Intent(this, MyOtherActivity.class);
intent.putExtra("map", hashMap);
startActivity(intent);
And then in the receiving Activity:

Intent intent = getIntent();
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("map");
String value = hashMap.get("key");

四、获取SD卡容量

private void getSDCardMemory() {
	StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); // SDCard       
	float blockSize = statFs.getBlockSize();
	float totalSize = statFs.getBlockCount() * blockSize;
	float availableSize = statFs.getAvailableBlocks() * blockSize;
	
	float total =  totalSize / 1073741824;
	float available = availableSize / 1073741824;
	
	LogUtil.error(TAG, String.format("SD卡总容量%.2fGB/剩余%.2fGB", total, available));
}

五、Intent 调用其它应用

// 拨打电话

// Intent.ACTION_CALL 直接拨打
// 需要权限  <uses-permission android:name="android.permission.CALL_PHONE" />
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:10086"));
startActivity(intent);


// 跳转应用市场评分

Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);

六、排序Map

// TreeMap

// TreeMap是一个有默认升序的Map
TreeMap<Integer, Boolean> map = new TreeMap<Integer, Boolean>();
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
     int key = (int) iterator.next();
     Log.e("key", "" + key);
}
        
// 降序
map.descendingMap()

七、Array 和 List 互转

// array to list
List<String> list = Arrays.asList(getResources().getStringArray(R.array.array_sort_title));
        
// list to array
String[] array = new String[list.size()];
list.toArray(array);

八、检查字符串是否为 URL 链接

Patterns.WEB_URL.matcher(“要检查的字符串”).matches()

Android Studio 

一、快捷键

Mac 版 Android Studio

// 代码补全
Ctrl + Alt + Space
这个和系统默认快捷键 显示Finder搜索窗口 冲突,两边至少要修改一边
    
// 删除单行
Command + Backspace

// 代码格式化
Command + Alt + L

// 剔除没有用到的引用
Ctrl + Alt + O

// 当前光标所在行 折叠、展开代码
Command + Alt + (+/-)

// 选中部分整体折叠
Command + Alt + T
格式
//<editor-fold desc="格式一">
...
//</editor-fold>

二、设置代码区域折叠

//<editor-fold desc="描述">
...
//</editor-fold>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值