1 Star 0 Fork 2

chenjim / kotlin-for-android-developers-zh

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
chuang_jian_yi_ge_she_zhi_activity.md 1.88 KB
一键复制 编辑 原始数据 按行查看 历史

创建一个设置activity

当toolbar上溢出菜单(overflow menu)的settings选项被点击时,需要打开一个新的Activity。所以首先要做的事情时需要一个新的SettingActivity

class SettingsActivity : AppCompatActivity() {
	
	override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)
        setSupportActionBar(toolbar)
        supportActionBar.setDisplayHomeAsUpEnabled(true)
    }

	override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
        android.R.id.home -> { onBackPressed(); true }
        else -> false
	}
}

当用户离开这个界面的时我们需要保存用户preference(偏好),所以我们需要像处理Back一样处理Up动作,重定向动作到onBackPressed。现在,让我们要创建一个XML布局。对于这个preference来说一个简单EditText就足够了:

<FrameLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<include layout="@layout/toolbar"/>
	<LinearLayout
		android:orientation="vertical"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_marginTop="?attr/actionBarSize"
		android:padding="@dimen/spacing_xlarge">
	
		<TextView
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/city_zipcode"/>
		
		<EditText
			android:id="@+id/cityCode"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:hint="@string/city_zipcode"
			android:inputType="number"/>

	</LinearLayout>
</FrameLayout>

然后只需要在AndroidManifest.xml中声明这个activity:

<activity
android:name=".ui.activities.SettingsActivity"
android:label="@string/settings"/>
1
https://gitee.com/chenjim/kotlin-for-android-developers-zh.git
git@gitee.com:chenjim/kotlin-for-android-developers-zh.git
chenjim
kotlin-for-android-developers-zh
kotlin-for-android-developers-zh
master

搜索帮助