I have added an ImageButton on the Actionbar. I have no idea how to make it clickable. Secondly, I want to hide the home logo button/image from the Actionbar. And finally I want to display a title on the Action Bar. Can anyone suggest me step by step what to do? My codes are as below:
actionbars.xml
<ImageView
android:id="@+id/actionBarLogo"
android:contentDescription="@string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:duplicateParentState="false"
android:focusable="false"
android:longClickable="false"
android:layout_marginLeft="225dp"
android:src="@drawable/settings" />
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.blue));
actionBar.setCustomView(R.layout.actionbars);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
ImageButton b=(ImageButton)findViewById(R.id.actionBarLogo);
b.setOnClickListener(new OnClickListener() {
//@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,Lists.class);
startActivity(i);
}
});
return super.onOptionsItemSelected(item);
}
}
If you're going to use a custom View
in your ActionBar
, you'll need to add it using a different method to make your ImageView
clickable. Here's an example of doing that along with hiding the home affordance.
// Initialize your custom layout
final View v = getLayoutInflater().inflate(R.layout.actionbars, null);
final ImageView iv = (ImageView) v.findViewById(R.id.actionBarLogo);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Called when your View is clicked
}
});
// Add the custom View to your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setCustomView(v);
actionBar.setDisplayShowCustomEnabled(true);
// Remove the "up" affordance
actionBar.setDisplayShowHomeEnabled(false);
Your ImageView
isn't a MenuItem
, that's why your app force closes in Activity.onOptionsItemSelected
.