[英]How to add a listener for the up button in ActionBar on Android?
[英]How to add click's listener for app's icon on ActionBar in Android?
有以下代码:
getActionBar().setIcon(R.drawable.basket);
现在,我想通过此图标设置用于单击的侦听器。 可能吗? 提前致谢!
在Activity的onCreate()处添加以下代码
mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
这是听众
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish(); // Or do you own task
return true;
}
return super.onOptionsItemSelected(item);
}
在“低级活动的添加按钮”中了解更多信息。 并且添加动作栏是有关ActionBar的很好的资源。
有两种制作自定义标题栏的方法:
1.如果您通过这种方式制作自定义标题
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);//xml class of your mainActivity
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title_bar);
/////custom_title_bar is xml of which type you want to make your title bar
然后,只需查找custom_title_bar中的小部件的ID,并在对mainactivity xml执行操作时执行操作即可。
只需将其作为活动xml的小部件即可
值-> menu.xml
<item
android:id="@+id/show"
android:showAsAction="always"
android:title="@string/show"
android:icon="@drawable/showbutn">
</item>
其中android:showAsAction="always"
,此行将项目放置在标题栏上
然后在您的mainactivity类中,将onOptionsItemSelected方法覆盖为:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.show:
///////perform your action what you want by clicking on item
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
而已....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.