Android小知识库

http://wuxiaolong.me/2015/08/10/android-small-knowledge-base/#rd 原文

Android小知识库

这份是我工作以来,总结的小知识库,有些知识点现在看来太LOW了,把还觉得有用的分享出来!

The APK file does not exist on disk.Error while Installing APK

解决方案:

Android Studio获取SHA1

1、全局配置jdk1.8.0_45\bin(或cd进入bin目录)
2、keytool -v -list -keystore 你的keystore路径
3、输入秘钥库口令:如果没设置,这里就是空,直接回车就进去了。

Genymotion下载虚拟镜像Connection timeout

Add new device出现的问题:

Failed to deploy virtual device.
Unable to create virtual device.Connection timeout occurred.

解决方案:

  1. 当选择Google Nexus 5 - 6.0.0 - API 23 - 1080x1920下载device失败后,到C:\Users\用户主目录\AppData\Local\Genymobile\Genymotion\ova下看到genymotion_vbox86p_6.0_160114_090449.ova,大小却是0KB,在C:\Users\用户主目录\AppData\Local\Genymobile\genymotion.log,打开该文件,找到类似“http://files2.genymotion.com/dists/6.0.0/ova/genymotion_vbox86p_6.0_160114_090449.ova”路径,即您想要下载的镜像文件URL;
  2. 用迅雷去下载,下载完成后放到C:\Users\用户主目录\AppData\Local\Genymobile\Genymotion\ova;
  3. 重新点击Google Nexus 5 - 6.0.0 - API 23 - 1080x1920去下载,验证安装后即会显示在设备列表中。

Android Studio 如何Debug

单击F5(Step Over),单行一个个方法执行
单击F6(Step Into),单行执行
单击F7(Step Out),不往下执行,回到上一行
单击F8(Resume Program),跳出当前断点

Android Studio设置默认的签名文件

新浪微博SSO登录,微信分享这些都需要签名打包,才能看到效果,设置默认签名文件为自己的签名jks,这样就不需要打包了。
在app目录下添加你的.jks,然后app的build.gradle文件中的增加以下内容:
第一种:

1
2
3
4
5
6
7
8
9
10
android {  
    signingConfigs {  
        debug {  
            storeFile file("你的.jks")
 storePassword 'android'
 keyAlias 'android'
 keyPassword 'android'
 } 
 } 
}

第二种:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
android {  
    signingConfigs {  
        release {  
            storeFile file("你的.jks")
 storePassword 'android'
 keyAlias 'android'
 keyPassword 'android'
 } 
 } 
 buildTypes {
        debug {
            signingConfig signingConfigs.release
        }        
    }
}

这样编译出来的debug版本直接用的是你的正式签名

Fragment懒加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
protected boolean isVisible;

   @Override
   public void setUserVisibleHint(boolean isVisibleToUser) {
       super.setUserVisibleHint(isVisibleToUser);
       if (getUserVisibleHint()) {
           isVisible = true;
           onVisible();
       } else {
           isVisible = false;
           onInvisible();
       }
   }

   protected void onVisible() {
      lazyLoad();
   }

   protected void lazyLoad() {
       if (!isVisible) {
           return;
       }
       getData();
   }

   protected void onInvisible() {
   }

Android studio头注释和方法注释

File | Settings | Editor|File and Code Templates|Includes|File Header

1
2
3
/**
 * Created by ${USER} on ${DATE}.
 */

输入我们想要设置的注释模板

adapter.getPositionForSelection()和getSectionForPosition()

getPositionForSection()根据分类列的索引号获得该序列的首个位置
getSectionForPosition()通过该项的位置,获得所在分类组的索引号

getResources().getColor(R.color.color_name) is deprecated和drawableTop

1
2
3
textView.setTextColor(Color.parseColor("#FFFFFF"));
//或者
ContextCompat.getColor(context, R.color.color_name)

showPopupWindow

1
2
3
4
5
6
7
8
9
10
11
12
13
private void showPopupMenu(View v) {
    final View bgView = View.inflate(DemoApplication.getContext(), R.layout.demo_popup_window_bg, null);
    bgView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hidePopupWindow();
        }
    });
    if (mPopupBackground == null) {
        mPopupBackground = new PopupWindow(bgView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }
    mPopupBackground.showAtLocation(v, Gravity.BOTTOM, 0, 0);
}

v:父布局
demo_popup_window_bg.xml

1
2
3
4
5
6
7
"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:background="@color/aliwx_common_alpha_black">

LinearLayout>

onFinishInflate()

view的onFinishInflate()何时调用的?
当View中所有的子控件均被映射成xml后触发;
MyView mv = (MyView)View.inflate (context,R.layout.my_view,null);
当加载完成xml后,就会执行那个方法;
我们一般使用View的流程是在onCreate中使用setContentView来设置要显示Layout文件或直接创建一个View,在当设置了ContentView之后系统会对这个View进行解析,然后回调当前视图View中的onFinishInflate方法。只有解析了这个View我们才能在这个View容器中获取到拥有Id的组件,同样因为系统解析完View之后才会调用onFinishInflate方法,所以我们自定义组件时可以onFinishInflate方法中获取指定子View的引用。

Fragment设置隐藏或显示某个Fragment

MainFragment点击

1
2
3
4
5
6
public void onItemClick(AdapterView adapterView, View view,  int position, long id) {
       
        ((MainActivity) getActivity()).showImageFragment(true, mData.get(position).get("title").toString(), mData.get(position).get("imgUrl").toString());
        
    }

MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
public void showImageFragment(boolean show, String imgTxt, String imgUrl) {
        // showActionbarWithTabs(!show);
        if (show) {
            getSupportFragmentManager().beginTransaction()
                    .show(imageDetailFragment).commit();
            imageDetailFragment.setImgData(imgTxt, imgUrl);
        } else {
            getSupportFragmentManager().beginTransaction()
                    .hide(imageDetailFragment).commit();
        }

    }

获取arrt的值

不同主题下需要把颜色,数值写成attr属性
xml里,我们可以简单的引用attr属性值

1
android:background="?attr/colorPrimary"

代码获取

1
2
3
TypedValue typedValue = new TypedValue();
mContext.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
int colorPrimary = typedValue.data;//value.data里面存储着的就是获取到的colorPrimary的值

拨号盘拨打电话

1
2
3
4
5
Intent intent = new Intent(Intent.ACTION_CALL,
Uri.parse("tel:" + "400-036-1977"));
// intent.setAction(Intent.ACTION_CALL);// 直接拨号
intent.setAction(Intent.ACTION_DIAL);// 拨号盘
startActivity(intent);

Drawable /Bitmap、String/InputStream、Bitmap/byte[]互转

http://wuxiaolong.me/2015/08/10/Drawable-to-Bitmap/

ProgressDialog

1
2
3
4
5
final ProgressDialog progress = new ProgressDialog(LoginActivity.this);
		progress.setMessage("请稍等...");
		progress.setCanceledOnTouchOutside(false);
		progress.show();
progress.dismiss();

毫秒

毫秒Calendar.getInstance().getTimeInMillis()和System.currentTimeMillis()

Fragment setUserVisibleHint(boolean isVisibleToUser)

1
2
3
4
5
6
7
8
9
@Override
   public void setUserVisibleHint(boolean isVisibleToUser) {
       super.setUserVisibleHint(isVisibleToUser);
       if (isVisibleToUser) {
           //相当于Fragment的onResume
       } else {
           //相当于Fragment的onPause
       }
   }

Fragment onActivityResult

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		getActivity();
		if (resultCode == Activity.RESULT_OK
				&& requestCode == AppUtils.REQUEST_CODE_ISLOGIN) {
			// 检查是否完善资料

			if (AppUtils.getSharedPreferences(getActivity()).getBoolean(
					"hasPersonalData", false)) {
				// 取本地存取是否完善资料,完善直接提示咨询对话框
				consultationDialog();
			} else {
				getCheckPersonalData();
			}

		}
	} 

startActivityForResult(intent,
							AppConfig.REQUEST_CODE_DIALOGUE);// 不是调用 getActivity().startActivityForResult()。

dimen代码取值

getDimension方法获取到资源文件中定义的dimension值。

1
2
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);

数组初始化赋值

1、创建数组后,通过循环对数组赋值。
例如代码:
int [] nums = new int [100];
for(int i=0;i<10;i++){
nums[i] = i;
}
2、例如代码:
int [] nums = {0,1,2,3,4,5,6,7,8,9};
3、int [] nums = new int[]{0,1,2,3,4,5,6,7,8,9};

Fragment.isAdded()

1
2
3
4
5
6
7
8
9
Fragment mBeforeFragment = new Fragment();
public void switchFragment(Fragment currentFragment) {
if (currentFragment.isAdded()) {
getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).show(currentFragment).commit();
} else {
getSupportFragmentManager().beginTransaction().hide(mBeforeFragment).add(R.id.container, currentFragment).commit();
}
mBeforeFragment = currentFragment;
}

调用:

1
switchFragment(HomeFragment.newInstance());

HomeFragment

1
2
3
4
5
6
7
8
public static HomeFragment homeFragment = null;

public static HomeFragment newInstance() {
if (homeFragment == null) {
homeFragment = new HomeFragment();
}
return homeFragment;
}

android之inputType属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"fill_parent" 
android:layout_height="wrap_content" 
android:inputType="phone" />
//文本类型,多为大写、小写和数字符号。
    android:inputType="none"
    android:inputType="text"
    android:inputType="textCapCharacters" 字母大写
    android:inputType="textCapWords" 首字母大写
    android:inputType="textCapSentences" 仅第一个字母大写
    android:inputType="textAutoCorrect" 自动完成
    android:inputType="textAutoComplete" 自动完成
    android:inputType="textMultiLine" 多行输入
    android:inputType="textImeMultiLine" 输入法多行(如果支持)
    android:inputType="textNoSuggestions" 不提示
    android:inputType="textUri" 网址
    android:inputType="textEmailAddress" 电子邮件地址
    android:inputType="textEmailSubject" 邮件主题
    android:inputType="textShortMessage" 短讯
    android:inputType="textLongMessage" 长信息
    android:inputType="textPersonName" 人名
    android:inputType="textPostalAddress" 地址
    android:inputType="textPassword" 密码
    android:inputType="textVisiblePassword" 可见密码
    android:inputType="textWebEditText" 作为网页表单的文本
    android:inputType="textFilter" 文本筛选过滤
    android:inputType="textPhonetic" 拼音输入
//数值类型
    android:inputType="number" 数字
    android:inputType="numberSigned" 带符号数字格式
    android:inputType="numberDecimal" 带小数点的浮点格式
    android:inputType="phone" 拨号键盘
    android:inputType="datetime" 时间日期
    android:inputType="date" 日期键盘
android:inputType="time" 时间键盘

ImageView.ScaleType

(1)ImageView.ScaleType.center:图片位于视图中间,但不执行缩放。
(2)ImageView.ScaleType.CENTER_CROP 按统一比例缩放图片(保持图片的尺寸比例)便于图片的两维(宽度和高度)等于或者大于相应的视图的维度
(3)ImageView.ScaleType.CENTER_INSIDE按统一比例缩放图片(保持图片的尺寸比例)便于图片的两维(宽度和高度)等于或者小于相应的视图的维度
(4)ImageView.ScaleType.FIT_CENTER缩放图片使用center
(5)ImageView.ScaleType.FIT_END缩放图片使用END
(6)ImageView.ScaleType.FIT_START缩放图片使用START
(7)ImageView.ScaleType.FIT_XY缩放图片使用XY
(8)ImageView.ScaleType.MATRIX当绘制时使用图片矩阵缩放

调用系统发送短信界面

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 发送短信
* @param smsBody
*/
private void sendSMS(String smsBody)
{
//Uri smsToUri = Uri.parse("smsto:10000"); //如果想指定发送人
Uri smsToUri = Uri.parse("smsto:");
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("sms_body", smsBody);
startActivity(intent);
}

跳转市场搜索某款软件

1
2
3
4
5
Intent intent = new Intent(
				"android.intent.action.VIEW");
		intent.setData(Uri
				.parse("market://details?id=com.adobe.flashplayer"));
		startActivity(intent);

检测系统中是否安装某款软件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//检测系统中是否已经安装了adobe flash player插件,插件的packageName是com.adobe.flashplayer:
private boolean check() {
		PackageManager pm = getPackageManager();
		List infoList = pm
				.getInstalledPackages(PackageManager.GET_SERVICES);
		for (PackageInfo info : infoList) {
			if ("com.adobe.flashplayer".equals(info.packageName)) {
				return true;
			}
		}
		return false;
}

private void isAvilible(String packageName) {

		PackageInfo packageInfo;
		try {
			packageInfo = this.getPackageManager().getPackageInfo(packageName,
					0);

		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo != null) {
//1、通过包名
			Intent intent = new Intent();
			intent = getPackageManager().getLaunchIntentForPackage(packageName);
			startActivity(intent);
//2、通过类名: 
Intent intent=new Intent();  
intent.setComponent(new ComponentName(packageName, "com.joe.internet.Main"));  
startActivity(intent);  
		} 

	}

对话框菜单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
new AlertDialog.Builder(this)
						.setTitle("choice")
						.setItems(new String[] { "选择1", "选择2", "选择3", "选择4" },
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,  int which) {
										Toast.makeText(MyContentActivity.this,
												which + "", Toast.LENGTH_SHORT)
												.show();

									}
								}).show();

定义ProgressBar

1
2
3
4

        android:id="@+id/mProgress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"          android:indeterminateDrawable="@drawable/progress_rotate" />

progress_rotate:

1
2
3
4
5
6
7
8
9
10
11
12
"1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
 <item>
 <rotate  android:drawable="@drawable/progressbar"  android:duration="300"  android:fromDegrees="0.0"  android:pivotX="50.0%"  android:pivotY="50.0%"  android:toDegrees="360.0" />
 item>
layer-list>

幻灯片效果

xml

1
2
3
4
5
6

        android:id="@+id/ProgressBar01"
        style="@style/animStyle"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true" />

style

1
2
3