Search code examples
androidandroid-fragmentsanimationandroid-viewpager

Animation for changing Action bar title for each fragment swipe on android


I have set up a custom Action bar with swipe (ViewPager) tabs using Toolbar Widget and Fragments.

I want to have different Action bar "title" for each tab. Also it would be great if i could set up an animation while swiping.

I would appreciate any suggestions and links to tutorials! Thanks in advance:)

MainActivity.Java

public class MainActivity extends FragmentActivity implements Json.Listener {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbar);
    topToolBar.setTitle("Weather");
    topToolBar.inflateMenu(R.menu.menu_home);
    topToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.add_city) {
                try {
                    AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
                            .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                            .build();
                    Intent intent =
                            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                                    .setFilter(typeFilter)
                                    .build(MainActivity.this);
                    startActivityForResult(intent, 1);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }
                return true;
            }

            return false;
        }
    });


    ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

    String city_name = (PreferenceManager.getDefaultSharedPreferences(this).getString("name", ""));;
    callAPI(city_name);

}

@Override
public void onLoaded(Response androidList) {
    new DBHandler(this).insertDetailsDB(androidList);
}

@Override
public void onError() {
    Toast.makeText(this, "Error !", Toast.LENGTH_SHORT).show();
}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
        switch (pos) {

            case 0:
                return new CityListFragment();
            case 1:
                return new WeatherDeatailsFragment();
            default:
                return new WeatherDeatailsFragment();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back"
tools:context="in.edu.apoorv.weather.MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"
    android:background="@android:color/transparent"
    android:layout_width="match_parent"
    android:titleTextColor="#fff"
    android:layout_height="60dp">
</android.support.v7.widget.Toolbar>


<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/viewPager"
    android:layout_marginTop="60dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />


Solution

  • You can do something like below

    1.Enclose a TextView inside your Toolbarlike this

    <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"
    android:background="@android:color/transparent"
    android:layout_width="match_parent"
    android:titleTextColor="#fff"
    android:layout_height="60dp">
    
        <TextView
        style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />      
    
    </android.support.v7.widget.Toolbar>
    

    2.Get the view in your activity

    TextView titleTv = (TextView) findViewById(R.id.toolbar_title);
    

    3.Create an animation xml file in res/anim folder.

    slide.xml

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true" >
    
    <scale
      android:duration="500"
      android:fromXScale="1.0"
      android:fromYScale="1.0"
      android:interpolator="@android:anim/linear_interpolator"
      android:toXScale="1.0"
      android:toYScale="0.0" />
    </set>
    

    4.Initialize the animation to the TextView.

    Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide);
    

    5.Set an OnPageChangeListener to your ViewPager. Call the animation in the onPageSelected() method of the listener.

    viewPager.setOnPageChangeListener(new OnPageChangeListener() {
        public void onPageScrollStateChanged(int state) {}
        public void onPageScrolled(int position, float positionOffset, int 
    positionOffsetPixels) {}
    
        public void onPageSelected(int position) {
    
             titleTv.startAnimation(animation1);
    
             switch(position){
             case 0:
                titleTv.setText("Title1");//set your title here
                break;
    
             case 1:
                titleTv.setText("Title2");//set your title here
                break;
            }
        }
    });
    

    I hope this works. :)