Calling Toolbar on each Activity

我们两清 提交于 2019-12-03 10:16:42

问题


My app has a toolbar that should be present on every view. Currently, I do the following in my onCreate() method for each Activity I have:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

Does this need to be done in every onCreate() method in every Activity or is there a simpler way? Also, as a side question, how can I implement a "back" feature in the toolbar that takes the user back one action if they click it?


回答1:


Create a Base class for Activity

public abstract class BaseActivity extends AppCompatActivity {

  Toolbar toolbar;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutResource());
    configureToolbar();
  }

  protected abstract int getLayoutResource();

  private void configureToolbar() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
      setSupportActionBar(toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        FragmentManager fm = getSupportFragmentManager();
        if (fm != null && fm.getBackStackEntryCount() > 0) {
          fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        } else {
          finish();
        }
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }
}

And in each Activity extends this BaseActivity to get the ToolBar and implementing the back feature.

At last don't forget to include the ToolBar in each activity layout.

Edit:

Override that method getLayoutResource() in each Activity and pass the layout id.

public class MainActivity extends BaseActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public int getLayoutResource() {
    return R.layout.activity_main;
  }



回答2:


This is my implementation. It removes the need of the getLayoutResources() from the accepted answer and brings back the "setContentView()" in all activities as normal

public abstract class BaseActivity extends AppCompatActivity {

    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    protected boolean useToolbar() {
        return true;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        configureToolbar(view);
        super.setContentView(view);
    }

    private void configureToolbar(View view) {
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        if (toolbar != null) {
            if (useToolbar()) {
                setSupportActionBar(toolbar);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            } else {
                toolbar.setVisibility(View.GONE);
            }
        }
    }
}

From here on you just extend BaseActivity. If you don't want a toolbar you will have to override the useToolbar().

Don't forget to add in activity.xml at the top

<include layout="@layout/toolbar" />

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</merge>



回答3:


It depends on your implementation but if you want avoid boilerplate code you should use good programming OO.

An Example using Fragment.

public abstract class FragmentBase extends Fragment {

    protected void settingsToolbar(View rootView) {

        Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);

        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        final ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            // TODO add your code and your requirements
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);

        }
    }




}

I hope this can give you an idea.




回答4:


If you have used Activity then Create BaseActivity that extends AppCompatActivity or ActionBarActivity(Deprecated) and move Toolbar code to BaseActivity.

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
}

If you have used Fragment then Create BaseFragment that extends Fragment and move Toolbar code to BaseFragment.

public class BaseFragment extends Fragment {

   View main;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        main = inflater.inflate(R.layout.fragment_about, container, false);
        Toolbar toolbar = (Toolbar) main.findViewById(R.id.toolbar);
        getActivity().setSupportActionBar(toolbar);
        return main;
    }
}

In main XML layout you have to add Toolbar xml code.

Now in every view(Activity) extends BaseActivity instead of AppCompatActivity or ActionBarActivity so you can get access Toolbar in every view.

public class YourActivity extends BaseActivity{
//your code
}

EDIT1:

main.xml

 <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:theme="@style/toolbarTheme"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/green"
            android:minHeight="?attr/actionBarSize" />

 </RelativeLayout>

EDIT2:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

add these two lines below setSupportActionBar(toolbar); in BaseActivity.

I hope it helps!




回答5:


Create a base activity and initialize your tool bar in this class. Now it can be extends to all other child activity.

FirtActivity extends BaseActivity

SecondActivity extends BaseActivity

In base activity toll bar back button click you can check like below mentioned way

if(this instance of FirstActivity){
  //do stuff here
}else if(this instance of SecondActivity){
 //do stuff here
}


来源:https://stackoverflow.com/questions/32367041/calling-toolbar-on-each-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!