admin管理员组文章数量:1532656
Android 常用API自查表
- Andriod Studio 升级后 Logcat提示:No connected devices
- 字体
- Android Studio 版本下载
- AndroidStudio 点9图生成
- IQOO Neo6 日志授权
- INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
- 移除和拷贝assets中的文件
- 清空任务栈
- CreateProcess error=206
- so打包大小写错误
- 拍照录像(JCameraView )
- 震动
- Google Demo
- 加入wifi列表
- gradle 依赖树
- Bitmap叠图
- 许可锁
- 获取IP
- 控件位置获取
- 获取指定大小的Drawable
- Drawable 旋转
- 重力感应
- 获取图片高宽
- 默认语言获取兼容7.0
- 获取 string 指定语言
- NOFrameLayout
- 隐藏显示
- SysBarTinManager
- StatusBarUtil(沉浸式状态栏)
- OSUtils
- StatusBarHeightView
Andriod Studio 升级后 Logcat提示:No connected devices
-
下载适用于 Windows 的 SDK Platform-Tools
-
解压后覆盖自己的SDK底下的adb文件
字体
#下载
https://freefonts.top/category/60ab1e40331cf308bd9e53f8?search=CN
#定制
https://fonts.google/?preview.text=OFF
Android Studio 版本下载
Google 官方
推荐
AndroidStudio 点9图生成
第一步
如下右键点击 Create 9-Patch file
第二步
- 文字部分不会变形
- 勾选 show patches 显示的绿色部分为放大部分
- 左右边黑色部分为标注放大范围,左方方大显示黑边,可用鼠标勾选,其他边也是如是操作
IQOO Neo6 日志授权
***QQ 加 3002261823 沟通***
日志打印授权
1.确认一下手机是国内系统还是国外系统(OriginOS是国内系统)
2.首先需要确认调试机器内bbklog版本高于7.2.6.2[通过*#*#112#*#*进入bbklog,右上角设置里可以看到,版本偏低请提出来,可以提供可授权的版本]
3.然后提供文本形式的调试机器imei1码给我,我这边会找人帮忙给开发者配置授权(拨号盘输入*#06#可以获取)
4.配置完成后,需要手动进入bbklog右上角更多界面,点击一键授权,授权后再尝试一下看看呢
麻烦按照这个提供一下信息
1.国内/国外系统
2.bbklog版本号是否符合授权要求
3.设备IMEI1
配置预计一个工作日内完成
INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
Android12以后,均需要manifest会检测
android:exported="false"
和 android:taskAffinity=""
而我的manifest是已经适配了的,经过检查发现如下
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
旧版本 打包后无法安装
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.10'
新版本 操作更简洁,可安装
想一探究竟,可直接双击debug.apk查看manifest
Leakcanary
移除和拷贝assets中的文件
删除
android.applicationVariants.all { variant ->
// if (variant.buildType.name == 'release') {//release版本,可以采用多渠道配置
variant.mergeAssets.doLast {
//删除assets文件夹下的所有zip文件,或者指定文件。(删除文件夹:文件夹名/**/*)
delete(fileTree(dir: variant.mergeAssets.outputDir, includes: ['A.json','*.zip','dirs/**/*']))
}
// }
}
拷贝
android.applicationVariants.all{ variant ->
delete "${buildDir}/intermediates/merged_assets/${variant.dirName}" // buildDir是app下的build目录
variant.mergeAssets.doLast{
def sourceDir = "${buildDir}/../" // 资源存放目录,这里是app下
print "${buildDir} \n" // 打印路径
copy { // 将from目录下的资源拷贝到into 下目录去
from "${sourceDir}/fromDir"
into "${outputDir}/res"
}
}
}
gradle-移除assets中的文件
清空任务栈
public static void enterLoginActivity(Context context) {
Intent intent = new Intent(context, LoginActivity.class);
//下面2个flags ,可以将原有任务栈清空
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
CreateProcess error=206
maximum-file-path-limitation(最大文件路径限制)
解决:创建注册表
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem]
"LongPathsEnabled"=dword:00000001
so打包大小写错误
android {
.
.
packagingOptions {
doNotStrip "**/*.so"
}
}
拍照录像(JCameraView )
import com.cjt2325.cameralibrary.JCameraView;
import com.cjt2325.cameralibrary.listener.ErrorListener;
import com.cjt2325.cameralibrary.listener.JCameraListener;
import com.cjt2325.cameralibrary.util.DeviceUtil;
import com.cjt2325.cameralibrary.util.FileUtil;
public class CameraActivity extends AppCompatActivity {
JCameraView jCameraView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_riderscamera);
init();
}
private void init() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
jCameraView = (JCameraView) findViewById(R.id.jcameraview);
//设置视频保存路径
jCameraView.setSaveVideoPath(Environment.getExternalStorageDirectory().getPath() + File.separator + "MyChat");
jCameraView.setFeatures(JCameraView.BUTTON_STATE_BOTH);
jCameraView.setTip("长按录视频");
jCameraView.setMediaQuality(JCameraView.MEDIA_QUALITY_HIGH);
jCameraView.setErrorLisenter(new ErrorListener() {
@Override
public void onError() {
//错误监听
Log.i("CJT", "camera error");
Intent intent = new Intent();
setResult(103, intent);
finish();
}
@Override
public void AudioPermissionError() {
Toast.makeText(CameraActivity.this, "给点录音权限可以?", Toast.LENGTH_SHORT).show();
}
});
jCameraView.setJCameraLisenter(new JCameraListener() {
@Override
public void captureSuccess(Bitmap bitmap) {
//获取图片bitmap
// Log.i("JCameraView", "bitmap = " + bitmap.getWidth());
String path = FileUtil.saveBitmap("JCamera", bitmap);
Intent intent = new Intent();
intent.putExtra("path", path);
setResult(101, intent);
finish();
}
@Override
public void recordSuccess(String url, Bitmap firstFrame) {
//获取视频路径
String path = FileUtil.saveBitmap("chatUtils", firstFrame);
Log.i("CJT", "url = " + url + ", Bitmap = " + path);
Intent intent = new Intent();
intent.putExtra("path", url);
intent.putExtra("bitmap", path);
setResult(102, intent);
finish();
}
});
Log.i("zyl", DeviceUtil.getDeviceModel());
}
@Override
protected void onStart() {
super.onStart();
//全屏显示
if (Build.VERSION.SDK_INT >= 19) {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
} else {
View decorView = getWindow().getDecorView();
int option = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(option);
}
}
@Override
protected void onResume() {
Log.i("CJT", "onResume");
super.onResume();
jCameraView.onResume();
}
@Override
protected void onPause() {
Log.i("CJT", "onPause");
super.onPause();
jCameraView.onPause();
}
}
震动
/**
* 文件名:VibratorPlayer
* 描 述:
* 作 者:
* 时 间:2021/9/15 17:31
*/
import android.content.Context;
import android.os.Vibrator;
public class VibratorPlayer {
private volatile boolean isVibrator;
private Vibrator vibrator;
private static VibratorPlayer vibratorPlayer;
public VibratorPlayer(Context context) {
vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
}
public static VibratorPlayer getInstance(Context context) {
if (vibratorPlayer == null) {
vibratorPlayer = new VibratorPlayer(context);
}
return vibratorPlayer;
}
/**
* 开始震动
*
* @param delay 延时时间
* @param interval 震动间隔
* @param isRepeat 是否重复
*/
public void play(long delay, long interval, boolean isRepeat) {
long[] pattern = {delay, interval};
vibrator.vibrate(pattern, isRepeat ? 0 : -1);
isVibrator = true;
}
/**
* 停止震动
*/
public void stop() {
isVibrator = false;
vibrator.cancel();
}
public void playOnece() {
if (isVibrator()) {
} else {
stop();
}
play(0, 150, false);
}
public boolean isVibrator() {
return isVibrator;
}
}
Google Demo
https://developer.android/samples
加入wifi列表
//保存到wifi列表 API30
Intent intent = new Intent(Settings.ACTION_WIFI_ADD_NETWORKS);
if (intent.resolveActivity(context.getPackageManager()) != null) {
intent.putParcelableArrayListExtra(Settings.EXTRA_WIFI_NETWORK_LIST, suggestionsList);
context.startActivityForResult(intent, Activity.RESULT_FIRST_USER);
}
gradle 依赖树
gradlew app:dependencies
Bitmap叠图
public static Bitmap drawBg4Bitmap(int color, Bitmap orginBitmap) {
Paint paint = new Paint();
paint.setColor(color);
Bitmap bitmap = Bitmap.createBitmap(orginBitmap.getWidth(),
orginBitmap.getHeight(), orginBitmap.getConfig());
Canvas canvas = new Canvas(bitmap);
paint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(orginBitmap, 0, 0, paint);
return bitmap;
}
许可锁
private Handler mHandler;
final Semaphore signal = new Semaphore(0);
new HandlerThread("xxxxxx"){
@Override
protected void onLooperPrepared() {
mHandler = new Handler();
signal.release();
}
}.start();
signal.acquireUninterruptibly();
private static CountDownLatch sSignal;
private static Handler sHandler;
static {
sSignal = new CountDownLatch(1);
new HandlerThread("xxxxxx"){
@Override
protected void onLooperPrepared() {
sHandler = new Handler();
sSignal.countDown();
}
}.start();
}
// Me make sure that we won't send Runnables to a non existing thread
try {
sSignal.await();
} catch (InterruptedException e) {}
获取IP
public static String displayIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
String ipaddress = "";
if (info!=null/* && info.getNetworkId()>-1*/) {
int i = info.getIpAddress();
String ip = String.format(Locale.ENGLISH,"%d.%d.%d.%d", i & 0xff, i >> 8 & 0xff,i >> 16 & 0xff,i >> 24 & 0xff);
ipaddress += "rtsp://";
ipaddress += ip;
ipaddress += ":";
ipaddress += DEFAULT_RTSP_PORT;
}
return ipaddress;
}
控件位置获取
//想对最外层控件
public class ViewUtils
{
private static final String FRAGMENT_CON = "NoSaveStateFrameLayout";
public static Rect getLocationInView(View parent, View child)
{
if (child == null || parent == null)
{
throw new IllegalArgumentException("parent and child can not be null .");
}
View decorView = null;
Context context = child.getContext();
if (context instanceof Activity)
{
decorView = ((Activity) context).getWindow().getDecorView();
}
Rect result = new Rect();
Rect tmpRect = new Rect();
View tmp = child;
if (child == parent)
{
child.getHitRect(result);
return result;
}
while (tmp != decorView && tmp != parent)
{
tmp.getHitRect(tmpRect);
if (!tmp.getClass().equals(FRAGMENT_CON))
{
result.left += tmpRect.left;
result.top += tmpRect.top;
}
tmp = (View) tmp.getParent();
//the wrong rect user will received in ViewPager
if(tmp.getParent() instanceof ViewPager){
tmp = (View) tmp.getParent();
}
}
result.right = result.left + child.getMeasuredWidth();
result.bottom = result.top + child.getMeasuredHeight();
return result;
}
}
获取指定大小的Drawable
fun drawableToBitmap(context: Context, drawableId: Int, width: Int = 0, height: Int = 0): Bitmap {
val drawable = ContextCompat.getDrawable(context, drawableId)
if (drawable is BitmapDrawable) {
return drawable.bitmap
}
val bitmap = if (width > 0 && height > 0) {
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
} else {
Bitmap.createBitmap(drawable!!.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
val canvas = Canvas(bitmap)
drawable!!.setBounds(0, 0, canvas.width, canvas.height)
drawable!!.draw(canvas)
return bitmap
}
Drawable 旋转
fun rotatDrawable(context: Context, drawable: Drawable, angle: Float): Drawable {
//创建一个Matrix对象
val matrix = Matrix()
//由darwable创建一个bitmap对象
var origin = (drawable as BitmapDrawable).bitmap
//设置旋转角度
matrix.setRotate(angle)
//以bitmap跟matrix一起创建一个新的旋转以后的bitmap
origin = Bitmap.createBitmap(origin, 0, 0, origin.width, origin.height, matrix, true)
val bitmapDrawable = BitmapDrawable(context.resources, origin)
//bitmap转化为drawable对象
return bitmapDrawable
}
重力感应
private var mOrientationEventListener: OrientationEventListener? = null
private var mLastOrientation: Int = 0
private fun initOrientationEventListener() {
if (mOrientationEventListener != null) {
mOrientationEventListener?.disable()
}
mOrientationEventListener = object : OrientationEventListener(ctx, SensorManager.SENSOR_DELAY_NORMAL) {
override fun onOrientationChanged(orientation: Int) {
var orientation = orientation
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return //手机平放时,检测不到有效的角度
}
//只检测是否有四个角度的改变
if (orientation > 350 || orientation < 10) { //0度
orientation = 0
} else if (orientation > 80 && orientation < 100) { //90度
orientation = 90
} else if (orientation > 170 && orientation < 190) { //180度
orientation = 180
} else if (orientation > 260 && orientation < 280) { //270度
orientation = 270
} else {
return
}
if (orientation == 0 && mLastOrientation != Surface.ROTATION_0) {
mLastOrientation = Surface.ROTATION_0
(ctx as Activity).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation == 180 && mLastOrientation != Surface.ROTATION_180) {
mLastOrientation = Surface.ROTATION_180
(ctx as Activity).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT)
}
}
}
}
//使用
initOrientationEventListener()
if (mOrientationEventListener?.canDetectOrientation()!!) {
mOrientationEventListener?.enable()
}
获取图片高宽
private fun getSaveFileSize(ifrPath: String) {
//图片尺寸
try {
val exif = ExifInterface(ifrPath)
savewidth = Integer.parseInt(exif?.getAttribute(ExifInterface.TAG_IMAGE_WIDTH) ?: "0")
saveheight = Integer.parseInt(exif?.getAttribute(ExifInterface.TAG_IMAGE_LENGTH) ?: "0")
} catch (e: FileNotFoundException) {
Log.d(TAG, "not find file:$ifrPath")
}
}
默认语言获取兼容7.0
Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locale = LocaleList.getDefault().get(0);
} else locale = Locale.getDefault();
String language = locale.getLanguage() + "-" + locale.getCountry();
获取 string 指定语言
public String getStringInDefaultLocale(Locale local, int resId) {
Resources currentResources = mContext.getResources();
AssetManager assets = currentResources.getAssets();
DisplayMetrics metrics = currentResources.getDisplayMetrics();
Configuration config = new Configuration(currentResources.getConfiguration());
config.locale = local;
Resources defaultLocaleResources = new Resources(assets, metrics, config);
String string = defaultLocaleResources.getString(resId);
return string;
}
NOFrameLayout
public class NoFrameLayout extends FrameLayout {
private boolean canTouch = true;
public NoFrameLayout(Context context) {
super(context);
}
public NoFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NoFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setCanTouch(boolean canTouch) {
this.canTouch = canTouch;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return canTouch;
}
}
隐藏显示
private fun seViewVisble(visble: Boolean) {
//注意:这里的LayoutParams根据当前demo_layout的父布类型取得,不然会报错
if (visble) {
val layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
layoutParams.gravity = Gravity.RIGHT or Gravity.CENTER_VERTICAL
demo_layout.layoutParams = layoutParams
} else {
demo_layout.layoutParams = FrameLayout.LayoutParams(Constants.ZERO, Constants.ZERO)
}
}
SysBarTinManager
/*
* Copyright (C) 2013 readyState Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout.LayoutParams;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Class to manage status and navigation bar tint effects when using KitKat
* translucent system UI modes.
*
*/
public class SystemBarTintManager {
/**
* The default system bar tint color value.
*/
public static final int DEFAULT_TINT_COLOR = 0x99000000;
private final SystemBarConfig mConfig;
private boolean mStatusBarAvailable;
private boolean mNavBarAvailable;
private boolean mStatusBarTintEnabled;
private boolean mNavBarTintEnabled;
private View mStatusBarTintView;
private View mNavBarTintView;
private static boolean sIsMiuiV6;
static {
try {
Class<?> sysClass = Class.forName("android.os.SystemProperties");
Method getStringMethod = sysClass.getDeclaredMethod("get", String.class);
sIsMiuiV6 = "V6".equals((String) getStringMethod.invoke(sysClass, "ro.miui.ui.version.name"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Constructor. Call this in the host activity onCreate method after its
* content view has been set. You should always create new instances when
* the host activity is recreated.
*
* @param activity The host activity.
*/
@TargetApi(19)
@SuppressWarnings("ResourceType")
public SystemBarTintManager(Activity activity) {
Window win = activity.getWindow();
ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// check theme attrs
int[] attrs = {android.R.attr.windowTranslucentStatus,
android.R.attr.windowTranslucentNavigation};
TypedArray a = activity.obtainStyledAttributes(attrs);
try {
mStatusBarAvailable = a.getBoolean(0, false);
mNavBarAvailable = a.getBoolean(1, false);
} finally {
a.recycle();
}
// check window flags
WindowManager.LayoutParams winParams = win.getAttributes();
int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if ((winParams.flags & bits) != 0) {
mStatusBarAvailable = true;
}
bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
if ((winParams.flags & bits) != 0) {
mNavBarAvailable = true;
}
}
mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
// device might not have virtual navigation keys
if (!mConfig.hasNavigtionBar()) {
mNavBarAvailable = false;
}
if (mStatusBarAvailable) {
setupStatusBarView(activity, decorViewGroup);
}
if (mNavBarAvailable) {
setupNavBarView(activity, decorViewGroup);
}
}
/**
* Enable tinting of the system status bar.
*
* If the platform is running Jelly Bean or earlier, or translucent system
* UI modes have not been enabled in either the theme or via window flags,
* then this method does nothing.
*
* @param enabled True to enable tinting, false to disable it (default).
*/
public void setStatusBarTintEnabled(boolean enabled) {
mStatusBarTintEnabled = enabled;
if (mStatusBarAvailable) {
mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* set status bar darkmode
* @param darkmode
* @param activity
*/
public void setStatusBarDarkMode(boolean darkmode, Activity activity) {
if (sIsMiuiV6) {
Class<? extends Window> clazz = activity.getWindow().getClass();
try {
int darkModeFlag = 0;
Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Enable tinting of the system navigation bar.
*
* If the platform does not have soft navigation keys, is running Jelly Bean
* or earlier, or translucent system UI modes have not been enabled in either
* the theme or via window flags, then this method does nothing.
*
* @param enabled True to enable tinting, false to disable it (default).
*/
public void setNavigationBarTintEnabled(boolean enabled) {
mNavBarTintEnabled = enabled;
if (mNavBarAvailable) {
mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* Apply the specified color tint to all system UI bars.
*
* @param color The color of the background tint.
*/
public void setTintColor(int color) {
setStatusBarTintColor(color);
setNavigationBarTintColor(color);
}
/**
* Apply the specified drawable or color resource to all system UI bars.
*
* @param res The identifier of the resource.
*/
public void setTintResource(int res) {
setStatusBarTintResource(res);
setNavigationBarTintResource(res);
}
/**
* Apply the specified drawable to all system UI bars.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
public void setTintDrawable(Drawable drawable) {
setStatusBarTintDrawable(drawable);
setNavigationBarTintDrawable(drawable);
}
/**
* Apply the specified alpha to all system UI bars.
*
* @param alpha The alpha to use
*/
public void setTintAlpha(float alpha) {
setStatusBarAlpha(alpha);
setNavigationBarAlpha(alpha);
}
/**
* Apply the specified color tint to the system status bar.
*
* @param color The color of the background tint.
*/
public void setStatusBarTintColor(int color) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system status bar.
*
* @param res The identifier of the resource.
*/
public void setStatusBarTintResource(int res) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system status bar.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
@SuppressWarnings("deprecation")
public void setStatusBarTintDrawable(Drawable drawable) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system status bar.
*
* @param alpha The alpha to use
*/
@TargetApi(11)
public void setStatusBarAlpha(float alpha) {
if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mStatusBarTintView.setAlpha(alpha);
}
}
/**
* Apply the specified color tint to the system navigation bar.
*
* @param color The color of the background tint.
*/
public void setNavigationBarTintColor(int color) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system navigation bar.
*
* @param res The identifier of the resource.
*/
public void setNavigationBarTintResource(int res) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system navigation bar.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
@SuppressWarnings("deprecation")
public void setNavigationBarTintDrawable(Drawable drawable) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system navigation bar.
*
* @param alpha The alpha to use
*/
@TargetApi(11)
public void setNavigationBarAlpha(float alpha) {
if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mNavBarTintView.setAlpha(alpha);
}
}
/**
* Get the system bar configuration.
*
* @return The system bar configuration for the current device configuration.
*/
public SystemBarConfig getConfig() {
return mConfig;
}
/**
* Is tinting enabled for the system status bar?
*
* @return True if enabled, False otherwise.
*/
public boolean isStatusBarTintEnabled() {
return mStatusBarTintEnabled;
}
/**
* Is tinting enabled for the system navigation bar?
*
* @return True if enabled, False otherwise.
*/
public boolean isNavBarTintEnabled() {
return mNavBarTintEnabled;
}
private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
mStatusBarTintView = new View(context);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
params.gravity = Gravity.TOP;
if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
params.rightMargin = mConfig.getNavigationBarWidth();
}
mStatusBarTintView.setLayoutParams(params);
mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mStatusBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mStatusBarTintView);
}
private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
mNavBarTintView = new View(context);
LayoutParams params;
if (mConfig.isNavigationAtBottom()) {
params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight());
params.gravity = Gravity.BOTTOM;
} else {
params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT);
params.gravity = Gravity.RIGHT;
}
mNavBarTintView.setLayoutParams(params);
mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mNavBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mNavBarTintView);
}
/**
* Class which describes system bar sizing and other characteristics for the current
* device configuration.
*
*/
public static class SystemBarConfig {
private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
private final boolean mTranslucentStatusBar;
private final boolean mTranslucentNavBar;
private final int mStatusBarHeight;
private final int mActionBarHeight;
private final boolean mHasNavigationBar;
private final int mNavigationBarHeight;
private final int mNavigationBarWidth;
private final boolean mInPortrait;
private final float mSmallestWidthDp;
private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
Resources res = activity.getResources();
mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
mSmallestWidthDp = getSmallestWidthDp(activity);
mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
mActionBarHeight = getActionBarHeight(activity);
mNavigationBarHeight = getNavigationBarHeight(activity);
mNavigationBarWidth = getNavigationBarWidth(activity);
mHasNavigationBar = (mNavigationBarHeight > 0);
mTranslucentStatusBar = translucentStatusBar;
mTranslucentNavBar = traslucentNavBar;
}
@TargetApi(14)
private int getActionBarHeight(Context context) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
result = context.getResources().getDimensionPixelSize(tv.resourceId);
}
return result;
}
@TargetApi(14)
private int getNavigationBarHeight(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (!ViewConfiguration.get(context).hasPermanentMenuKey()) {
String key;
if (mInPortrait) {
key = NAV_BAR_HEIGHT_RES_NAME;
} else {
key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
}
return getInternalDimensionSize(res, key);
}
}
return result;
}
@TargetApi(14)
private int getNavigationBarWidth(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (!ViewConfiguration.get(context).hasPermanentMenuKey()) {
return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
}
}
return result;
}
private int getInternalDimensionSize(Resources res, String key) {
int result = 0;
int resourceId = res.getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
return result;
}
@SuppressLint("NewApi")
private float getSmallestWidthDp(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
} else {
// TODO this is not correct, but we don't really care pre-kitkat
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
}
float widthDp = metrics.widthPixels / metrics.density;
float heightDp = metrics.heightPixels / metrics.density;
return Math.min(widthDp, heightDp);
}
/**
* Should a navigation bar appear at the bottom of the screen in the current
* device configuration? A navigation bar may appear on the right side of
* the screen in certain configurations.
*
* @return True if navigation should appear at the bottom of the screen, False otherwise.
*/
public boolean isNavigationAtBottom() {
return (mSmallestWidthDp >= 600 || mInPortrait);
}
/**
* Get the height of the system status bar.
*
* @return The height of the status bar (in pixels).
*/
public int getStatusBarHeight() {
return mStatusBarHeight;
}
/**
* Get the height of the action bar.
*
* @return The height of the action bar (in pixels).
*/
public int getActionBarHeight() {
return mActionBarHeight;
}
/**
* Does this device have a system navigation bar?
*
* @return True if this device uses soft key navigation, False otherwise.
*/
public boolean hasNavigtionBar() {
return mHasNavigationBar;
}
/**
* Get the height of the system navigation bar.
*
* @return The height of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarHeight() {
return mNavigationBarHeight;
}
/**
* Get the width of the system navigation bar when it is placed vertically on the screen.
*
* @return The width of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarWidth() {
return mNavigationBarWidth;
}
/**
* Get the layout inset for any system UI that appears at the top of the screen.
*
* @param withActionBar True to include the height of the action bar, False otherwise.
* @return The layout inset (in pixels).
*/
public int getPixelInsetTop(boolean withActionBar) {
return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0);
}
/**
* Get the layout inset for any system UI that appears at the bottom of the screen.
*
* @return The layout inset (in pixels).
*/
public int getPixelInsetBottom() {
if (mTranslucentNavBar && isNavigationAtBottom()) {
return mNavigationBarHeight;
} else {
return 0;
}
}
/**
* Get the layout inset for any system UI that appears at the right of the screen.
*
* @return The layout inset (in pixels).
*/
public int getPixelInsetRight() {
if (mTranslucentNavBar && !isNavigationAtBottom()) {
return mNavigationBarWidth;
} else {
return 0;
}
}
}
}
StatusBarUtil(沉浸式状态栏)
切记关闭状态栏 自动填充
android:fitsSystemWindows="false"
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.IntDef;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class StatusBarUtil {
public final static int TYPE_MIUI = 0;
public final static int TYPE_FLYME = 1;
public final static int TYPE_M = 3;//6.0
@IntDef({TYPE_MIUI,
TYPE_FLYME,
TYPE_M})
@Retention(RetentionPolicy.SOURCE)
@interface ViewType {
}
/**
* 修改状态栏颜色,支持4.4以上版本
*
* @param colorId 颜色
*/
public static void setStatusBarColor(Activity activity, int colorId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.setStatusBarColor(colorId);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//使用SystemBarTintManager,需要先将状态栏设置为透明
setTranslucentStatus(activity);
SystemBarTintManager systemBarTintManager = new SystemBarTintManager(activity);
systemBarTintManager.setStatusBarTintEnabled(true);//显示状态栏
systemBarTintManager.setStatusBarTintColor(colorId);//设置状态栏颜色
}
}
/**
* 设置状态栏透明
*/
@TargetApi(19)
public static void setTranslucentStatus(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//5.x开始需要把颜色设置透明,否则导航栏会呈现系统默认的浅灰色
Window window = activity.getWindow();
View decorView = window.getDecorView();
//两个 flag 要结合使用,表示让应用的主体内容占用系统状态栏的空间
int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
decorView.setSystemUiVisibility(option);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
//导航栏颜色也可以正常设置
//window.setNavigationBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = activity.getWindow();
WindowManager.LayoutParams attributes = window.getAttributes();
int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
attributes.flags |= flagTranslucentStatus;
//int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
//attributes.flags |= flagTranslucentNavigation;
window.setAttributes(attributes);
}
}
/**
* 代码实现android:fitsSystemWindows
*
* @param activity
*/
public static void setRootViewFitsSystemWindows(Activity activity, boolean fitSystemWindows) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ViewGroup winContent = (ViewGroup) activity.findViewById(android.R.id.content);
if (winContent.getChildCount() > 0) {
ViewGroup rootView = (ViewGroup) winContent.getChildAt(0);
if (rootView != null) {
rootView.setFitsSystemWindows(fitSystemWindows);
}
}
}
}
/**
* 设置状态栏深色浅色切换
*/
public static boolean setStatusBarDarkTheme(Activity activity, boolean dark) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setStatusBarFontIconDark(activity, TYPE_M, dark);
} else if (OSUtils.isMiui()) {
setStatusBarFontIconDark(activity, TYPE_MIUI, dark);
} else if (OSUtils.isFlyme()) {
setStatusBarFontIconDark(activity, TYPE_FLYME, dark);
} else {//其他情况
return false;
}
return true;
}
return false;
}
/**
* 设置 状态栏深色浅色切换
*/
public static boolean setStatusBarFontIconDark(Activity activity, @ViewType int type,boolean dark) {
switch (type) {
case TYPE_MIUI:
return setMiuiUI(activity, dark);
case TYPE_FLYME:
return setFlymeUI(activity, dark);
case TYPE_M:
default:
return setCommonUI(activity,dark);
}
}
//设置6.0 状态栏深色浅色切换
public static boolean setCommonUI(Activity activity, boolean dark) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decorView = activity.getWindow().getDecorView();
if (decorView != null) {
int vis = decorView.getSystemUiVisibility();
if (dark) {
vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
} else {
vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
}
if (decorView.getSystemUiVisibility() != vis) {
decorView.setSystemUiVisibility(vis);
}
return true;
}
}
return false;
}
//设置Flyme 状态栏深色浅色切换
public static boolean setFlymeUI(Activity activity, boolean dark) {
try {
Window window = activity.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(lp);
if (dark) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(lp, value);
window.setAttributes(lp);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//设置MIUI 状态栏深色浅色切换
public static boolean setMiuiUI(Activity activity, boolean dark) {
try {
Window window = activity.getWindow();
Class<?> clazz = activity.getWindow().getClass();
@SuppressLint("PrivateApi") Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
int darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getDeclaredMethod("setExtraFlags", int.class, int.class);
extraFlagField.setAccessible(true);
if (dark) { //状态栏亮色且黑色字体
extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
} else {
extraFlagField.invoke(window, 0, darkModeFlag);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//获取状态栏高度
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier(
"status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
}
OSUtils
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static com.cjoe.utils.IntentUtil.getAppDetailsSettingsIntent;
public class OSUtils {
public static final String ROM_MIUI = "MIUI";
public static final String ROM_EMUI = "EMUI";
public static final String ROM_FLYME = "FLYME";
public static final String ROM_OPPO = "OPPO";
public static final String ROM_SMARTISAN = "SMARTISAN";
public static final String ROM_VIVO = "VIVO";
public static final String ROM_QIKU = "QIKU";
private static final String KEY_VERSION_MIUI = "ro.miui.ui.version.name";
private static final String KEY_VERSION_EMUI = "ro.build.version.emui";
private static final String KEY_VERSION_OPPO = "ro.build.version.opporom";
private static final String KEY_VERSION_SMARTISAN = "ro.smartisan.version";
private static final String KEY_VERSION_VIVO = "ro.vivo.os.version";
private static String sName;
private static String sVersion;
public static boolean isEmui() {
return check(ROM_EMUI);
}
public static boolean isMiui() {
return check(ROM_MIUI);
}
public static boolean isVivo() {
return check(ROM_VIVO);
}
public static boolean isOppo() {
return check(ROM_OPPO);
}
public static boolean isFlyme() {
return check(ROM_FLYME);
}
public static boolean is360() {
return check(ROM_QIKU) || check("360");
}
public static boolean isSmartisan() {
return check(ROM_SMARTISAN);
}
public static String getName() {
if (sName == null) {
check("");
}
return sName;
}
public static String getVersion() {
if (sVersion == null) {
check("");
}
return sVersion;
}
public static boolean check(String rom) {
if (sName != null) {
return sName.equals(rom);
}
if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_MIUI))) {
sName = ROM_MIUI;
} else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_EMUI))) {
sName = ROM_EMUI;
} else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_OPPO))) {
sName = ROM_OPPO;
} else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_VIVO))) {
sName = ROM_VIVO;
} else if (!TextUtils.isEmpty(sVersion = getProp(KEY_VERSION_SMARTISAN))) {
sName = ROM_SMARTISAN;
} else {
sVersion = Build.DISPLAY;
if (sVersion.toUpperCase().contains(ROM_FLYME)) {
sName = ROM_FLYME;
} else {
sVersion = Build.UNKNOWN;
sName = Build.MANUFACTURER.toUpperCase();
}
}
return sName.equals(rom);
}
public static Intent getSettingsIntent(Context mCt) {
Intent intent = new Intent();
String packageName = mCt.getPackageName();
if (isFlyme()) {
intent.setAction("com.meizu.safe.security.SHOW_APPSEC");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("packageName", packageName);
} else if (isEmui()) {
intent.putExtra("packageName", packageName);
intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity"));
} else if (isMiui()) {
String rom = getMiuiVersion();
if ("V6".equals(rom) || "V7".equals(rom)) {
intent.setAction("miui.intent.action.APP_PERM_EDITOR");
intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
intent.putExtra("extra_pkgname", packageName);
} else if ("V8".equals(rom) || "V9".equals(rom)) {
intent.setAction("miui.intent.action.APP_PERM_EDITOR");
intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
intent.putExtra("extra_pkgname", packageName);
}
} else if (isFlyme()) {
intent.setAction("com.meizu.safe.security.SHOW_APPSEC");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("packageName", packageName);
} else if (isOppo()) {
intent.putExtra("packageName", packageName);
intent.setComponent(new ComponentName("com.coloros.securitypermission", "com.coloros.securitypermission.permission.PermissionGroupsActivity"));
} else {
intent = getAppDetailsSettingsIntent(packageName);
}
// intent.putExtra("packageName", packageName);
// intent.setComponent(new ComponentName("com.sonymobile.cta", "com.sonymobile.cta.SomcCTAMainActivity"));
// case EUI: // 乐视
// intent.putExtra("packageName", packageName);
// intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.PermissionAndApps"));
// case LG: // LG
// intent.setAction("android.intent.action.MAIN");
// intent.putExtra("packageName", packageName);
// ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$AccessLockSummaryActivity");
// intent.setComponent(comp);
return intent;
}
public static String getProp(String name) {
String line = null;
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("getprop " + name);
input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
line = input.readLine();
input.close();
} catch (IOException ex) {
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return line;
}
private static String getMiuiVersion() {
String propName = "ro.miui.ui.version.name";
String line;
BufferedReader input = null;
try {
Process p = Runtime.getRuntime().exec("getprop " + propName);
input = new BufferedReader(
new InputStreamReader(p.getInputStream()), 1024);
line = input.readLine();
input.close();
} catch (IOException ex) {
ex.printStackTrace();
return null;
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return line;
}
}
StatusBarHeightView
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.LinearLayout;
/**
* 功能:状态栏高度View,用于沉浸占位
*/
public class StatusBarHeightView extends LinearLayout {
private int statusBarHeight;
private int type;
public StatusBarHeightView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public StatusBarHeightView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
public StatusBarHeightView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(@Nullable AttributeSet attrs) {
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if(resourceId>0) {
statusBarHeight = getResources().getDimensionPixelSize(resourceId)+100;
}
}else{
//低版本 直接设置0
statusBarHeight = 0;
}
if (attrs != null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.StatusBarHeightView);
type = typedArray.getInt(R.styleable.StatusBarHeightView_use_type, 0);
typedArray.recycle();
}
if (type == 1) {
setPadding(getPaddingLeft(), statusBarHeight, getPaddingRight(), getPaddingBottom());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (type == 0) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
statusBarHeight);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
版权声明:本文标题:Android 常用API自查表(二) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1726325954a1065800.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论