Android toolbar change layout
Asked Answered
S

2

6

I got an activity with many fragments. When i change fragments i need to change also and my toolbar declared in MainActivity.class. My problem is that i include a layout and didnt find a method to change this layout. How to change toolbars layout in this case? MainActivity.class

 @ContentView(R.layout.activity_main)
    public class MainActivity extends RoboActionBarActivity {

        @InjectView(R.id.tool_bar)
        Toolbar toolbar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setToolBar();
            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, new SplashFragment())
                        .commit();
            } else {
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, new HomeFragment())
                        .commit();
            }
        }
    private void setToolBar() {
            setSupportActionBar(toolbar);
        }

        @Override
        public void onAttachFragment(Fragment fragment) {
            super.onAttachFragment(fragment);
            String currentFragmentClass = fragment.getClass().getSimpleName();
            if (currentFragmentClass.equals(getString(R.string.info_fragment))) {
    //here i need to change and set onclicks
            }
        }
    }

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activities.MainActivity">

        <include
            android:id="@+id/tool_bar"
            layout="@layout/tool_bar" />

        <View
            android:id="@+id/shadow_view"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_below="@+id/tool_bar"
            android:background="#ad8c22" />

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/shadow_view"
            tools:context=".activities.MainActivity"
            tools:ignore="MergeRootFrame" />
    </RelativeLayout>

tool_bar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorToolBar"
    >
    <RelativeLayout
        android:id="@+id/toolbar_main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:onClick="toggleSlidingMenu"
            android:src="@mipmap/icon_sliding_menu" />
        <ImageView
            android:id="@+id/app_logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@mipmap/jammboree" />
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/app_logo"
            android:padding="5dp">
            <ImageView
                android:id="@+id/hotlist_bell"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:contentDescription="bell"
                android:gravity="center"
                android:padding="7dp"
                android:src="@mipmap/icon_my_cart" />
            <TextView
                android:id="@+id/hotlist_hot"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignRight="@id/hotlist_bell"
                android:layout_alignTop="@id/hotlist_bell"
                android:background="@drawable/rounded_square"
                android:gravity="center"
                android:minWidth="17sp"
                android:padding="2dp"
                android:text="2"
                android:textColor="#ffffffff"
                android:textSize="12sp" />
            <TextView
                android:id="@+id/myMoneyInMyPocket"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/hotlist_bell"
                android:text="2000$"
                android:textColor="#ffffff"
                android:textSize="14sp"
                android:textStyle="bold" />
        </RelativeLayout>
    </RelativeLayout>
</android.support.v7.widget.Toolbar>
Sacha answered 17/2, 2016 at 21:18 Comment(1)
My answer to a similar question was up-voted. #35304130. Does it help?Prosimian
U
9

If I understood right, you want to change the toolbar whenever you change the Fragment the user is currently seeing, isn´t that right?

There is a very simple way to achieve this trough your XML. Let's say you want three different styled toolbars.

1) First, you create XML files for every toolbar you need.

2) Then you include every toolbar in to your activity_main.xml, like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <include
        android:id="@+id/toolbar1"
        layout="@layout/tool_bar1"
        android:visibility="visible" />

    <include
        android:id="@+id/toolbar2"
        layout="@layout/tool_bar2"
        android:visibility="gone" />

    <include
        android:id="@+id/toolbar3"
        layout="@layout/tool_bar3"
        android:visibility="gone" />

    // Here is the rest of your XML code

</RelativeLayout>

See how all three toolbar includes have the visibility property?

Well, now you can toy with this property, and show/hide the desired toolbar whenever you want/need to.

For example:

RelativeLayout mLayout = (RelativeLayout) getActivity().findViewById(R.id.my_main_layout);

Toolbar mToolbar1 = (Toolbar) mLayout.findViewById(R.id.toolbar1);
mToolbar1.setVisibility(View.GONE);

Toolbar mToolbar2 = (Toolbar) mLayout.findViewById(R.id.toolbar2);
mToolbar2.setVisibility(View.GONE);

Toolbar mToolbar3 = (Toolbar) mLayout.findViewById(R.id.toolbar3);
mToolbar3.setVisibility(View.VISIBLE);

And just change which one are you making visible, according to your needs.

Hope this helps.

Unilingual answered 17/2, 2016 at 23:25 Comment(2)
Doesn't every toolbar occupy space in the memory even if the visibility is GONE? What happens when you have a big app with 20 different toolbars?Alemanni
@AlexBusuioc I haven't tried it myself, but redrawing views and having your layout recalculate where to paint them isn't particularly extra good for performance. A .GONE view saves you that part, I guess you could measure which version is better for your use case.Unilingual
A
1

I don`t think the method of @herrmartell is nice;

In my way,I have three Fragment in a Activity,I defined some different layout resources for a common toolbar xml,and load them in toolbar when I click different button; my code :

  1. common_toolbar xml:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
    
    <!-- your custom layout -->
    
    </android.support.v7.widget.Toolbar>
    
  2. activity_main_toolbar_common_view.xml

    <TextView
        android:id="@+id/action_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="迪士尼...ˇ"
        android:textColor="@color/white"
        android:textSize="@dimen/larget_text_size"
        android:paddingLeft="10dp"
        android:layout_alignParentStart="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"/>
    

  3. activity_main_toolbar_mine_view.xml

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/mine"
        android:textSize="@dimen/big_text_size"
        android:textColor="@color/white"
        android:gravity="center"
        android:layout_centerInParent="true"/>
    
    <ImageView
        android:id="@+id/setting"
        android:layout_width="@dimen/toolbar_icon_size"
        android:layout_height="@dimen/toolbar_icon_size"
        android:src="@drawable/toolbar_setting"
        android:layout_alignParentRight="true"
       />
    

  4. switchToolbar() method in Activity:

    public void switchToolbar(int layout) {
        if(currentToolbarLayout == layout){
            return;
        }
        currentToolbarLayout = layout;
        View  v = getLayoutInflater().inflate(layout,null);
        toolbar.removeAllViews();
        toolbar.addView(v);
    
        switch (layout){
            case R.layout.activity_main_toolbar_common_view:
                v.findViewById(R.id.action_location).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "跳到位置", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.layout.activity_main_toolbar_mine_view:
                v.findViewById(R.id.setting).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "跳到设置", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
        }
    }
    
  5. I render my toolbar view in the onCreate() method of Activity:

    ButterKnife.bind(this);
    setSupportActionBar(toolbar);
    switchToolbar(R.layout.activity_main_toolbar_common_view);
    
  6. when I switch toolbar, I call:

    switchToolbar(R.layout.activity_main_toolbar_mine_view);
    
Attendance answered 24/3, 2018 at 13:51 Comment(3)
This is fine, but takes more effort to write & maintain, and doesn't really offer a performance benefit. Also, your solution doesn't really address changing the toolbar attributes per se, i.e. background & foreground colors, height, etc. Remember that you should always try to keep your code as simple and as clean as possible.Unilingual
I like this better tbh; over time the fragments in the MainActivity will change. I don't see the maintainability in putting all of the specific toolbars in the MainActivity. Especially when the custom toolbars are complex.Benadryl
To add to @Unilingual comment. It is easy to retain the last instance of the views inside toolbar without much overhead. Removing all views and then attaching views make you lose the instance of the view and you need to recreate it. So for my usecase scenario I go with hermartell.Washtub

© 2022 - 2024 — McMap. All rights reserved.