android – How to get actionbar back button width programmatically?-ThrowExceptions

Exception or error:

I am setting toolbar to my actionbar, but I have activities when I disable home button and the title in toolbar is not centralized so I would like to get actionbar back button with programmatically to set toolbar.setContentInsetsAbsolute(0, 0);

enter image description here

How to solve:

try this

     toolbar = (Toolbar) findViewById(R.id.toolbar_editprofile);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
  toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

###

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

###

You can set by setting Style, set activity theme in the manifest as no action bar and use toolbar manually in layout and set the style as you want and you can also change the size of text or you can inflate image in toolbar by using style.

 <style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
    <item name="android:homeAsUpIndicator">@drawable/ic_toolbar_back_button</item>
</style>

 <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?actionBarSize"
                    android:layout_gravity="top"
                    android:background="@android:color/transparent"
                    android:visibility="visible"
                    app:theme="@style/Theme.MyFancyTheme">

###

You need to do something like this for the TextView inside the Toolbar which contains your title:

android:paddingLeft="?attr/actionBarSize"

Leave a Reply

Your email address will not be published. Required fields are marked *