1.跳转Activity
常规方式
var intent = Intent(this@MainActivity,MainActivity::class.java) intent.putExtra("name","wang") intent.putExtra("age",20) startActivity(intent)
使用anko
导入依赖:
startActivity<MainActivity>( "name" to "wang", "age" to 20, Pair("major","computer") )
2.类型序列化
使用 data class ,再加上@Parcelize注解
@Parcelize data class User(var name:String) { }
在build.gradle里添加
plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-android-extensions' 新添加 }
android { compileSdk 31 defaultConfig { applicationId "com.example.kotlindemo" minSdk 29 targetSdk 31 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } androidExtensions { 新添加 experimental = true } }
3.在输入完成后,自动隐藏输入法
//定义一个编辑框监听器,在输入文本达到指定长度时自动隐藏输入法 private class HideTextWatcher implements TextWatcher { private EditText mView; private int mMaxLength; private CharSequence mStr; public HideTextWatcher(EditText v) { super(); mView = v; //通过反射机制获取编辑框的最大长度 mMaxLength = ViewUtil.getMaxLength(v); } //在编辑框的输入文本变化前触发 @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } //在编辑框的输入文本变化时触发 @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mStr = s; } //在编辑框输入文本变化后触发 @Override public void afterTextChanged(Editable s) { if (mStr == null || mStr.length() ==0) { return; } //输入文本达到11位(如手机号码)时关闭输入法 if (mStr.length() == 11 && mMaxLength == 11) { ViewUtil.hideAllInputMethod(EditHideActivity.this); } //输入文本达到6位(如登录密码)时关闭输入法 if (mStr.length() == 6 && mMaxLength ==6) { ViewUtil.hideOneInputMethod(EditHideActivity.this, mView); } } }
public static void hideAllInputMethod(Activity act) { //从系统服务中获取输入法管理器 InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm.isActive()) { //软键盘如果已经打开则关闭之 imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); } } public static void hideOneInputMethod(Activity act, View v) { //从系统服务中获取输入法管理器 InputMethodManager imm = (InputMethodManager)act.getSystemService(Context.INPUT_METHOD_SERVICE); //关闭屏幕上的输入法软键盘 imm.hideSoftInputFromWindow(v.getWindowToken(), 0); }