I try to implement a custom action bar. Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/action_bar">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="test "/>
</FrameLayout>
And here is the java code:
public class CustomActionBarActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayOptions(android.support.v7.app.ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
View customView = getLayoutInflater().inflate(R.layout.action_bar, null);
actionBar.setCustomView(customView);
Toolbar parent = (Toolbar) customView.getParent();
parent.setContentInsetsAbsolute(0, 0);
}
}
The result is:
Here is the result with "developer options" > "show layout bounds"
As @Muhannad Fakhouri in comment pointed out. I needed to add layout params programatically. Layout params will be ignored if the layout inflated without specifying the parent. Here is the updated code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayOptions(android.support.v7.app.ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
View customView = getLayoutInflater().inflate(R.layout.action_bar, null);
customView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
actionBar.setCustomView(customView);
Toolbar parent = (Toolbar) customView.getParent();
parent.setContentInsetsAbsolute(0, 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With