我发现这篇文章如何添加一个开关到android动作栏? 这对我有用.但我不能得到它的事件.我正在使用appcompat,我使用了app命名空间for actionLayout和showAsAction,但是我无法处理它对onOptionsItemSelected方法的点击?我的应用程序在启动时崩溃了.如何处理它或这段代码有什么问题?这是我的代码
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<item
android:id="@+id/myswitch"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/switch_layout"/>
Run Code Online (Sandbox Code Playgroud)
switch_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Switch
android:id="@+id/switchForActionBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.your_menu, menu);
MenuItem menuItem= menu.findItem(R.id.myswitch);
Switch switcha = (Switch)menuItem.findViewById(R.id.switchForActionBar);
switcha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do anything here on check changed
}
});
return super.onCreateOptionsMenu(menu);
}
Run Code Online (Sandbox Code Playgroud)
和
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.myswitch) {
//do something
}
return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助都非常感谢.提前致谢.
Ami*_*mir 14
我发现了我的错误.我必须使用
View view = MenuItemCompat.getActionView(menuItem);
onCreateOptionsMenu中的额外行以找出切换按钮.这是我的完整方法
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.myswitch);
View view = MenuItemCompat.getActionView(menuItem);
Switch switcha = (Switch) view.findViewById(R.id.switchForActionBar);
switcha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do anything here on check changed
}
});
return super.onCreateOptionsMenu(menu);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1418 次 |
| 最近记录: |