O
O
Oleksiy2015-12-31 12:38:43
Android
Oleksiy, 2015-12-31 12:38:43

How to change fragment to another fragment on button click?

Hello Grandfather Frost and Snow Maiden! The third day I try to deal with the problem and reached a dead end ... Obviously I missed something, but what? Please help me get back on the path of truth. :)
So, the task is: when you press the button in Fragment1, replace it with Fragment1.1.
We have the following:
activity_main.xml

<LinearLayout
    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="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/orange"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="@string/app_name" />
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    <FrameLayout
        android:id="@+id/containerView"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
     </FrameLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/shitstuff"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:itemTextColor="@color/black"
        app:menu="@menu/drawermenu"
        android:layout_marginTop="-24dp" />
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

MainActivity.java
package com.s.MR;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
    DrawerLayout mDrawerLayout;
    NavigationView mNavigationView;
    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /// Настройка DrawerLayout и NavigationView
             mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
             mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
        /// inflate самый первый fragment, потом в нём inflating TabFragment как первый Fragment
             mFragmentManager = getSupportFragmentManager();
             mFragmentTransaction = mFragmentManager.beginTransaction();
             mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
        /// Настройка событий по click'у на элементы Navigation View
             mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                 @Override
                 public boolean onNavigationItemSelected(MenuItem menuItem) {
                     mDrawerLayout.closeDrawers();
                     if (menuItem.getItemId() == R.id.send) {
                         FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                         fragmentTransaction.replace(R.id.containerView, new Fragment_Send()).commit();
                     }
                     if (menuItem.getItemId() == R.id.nav_home) {
                         FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                         xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
                     }
                     if (menuItem.getItemId() == R.id.favorites) {
                         FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                         xfragmentTransaction.replace(R.id.containerView, new Fragment1_1()).commit();
                     }
                     return false;
                 }
        /// Настройка кнопок разделов
             });
        /// Настройка Drawer Toggle в Toolbar
                android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
                ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name, R.string.app_name);
                mDrawerLayout.setDrawerListener(mDrawerToggle);
                mDrawerToggle.syncState();
                /// Иконка приложения в toolbar'е
                toolbar.setLogo(R.mipmap.ic_launcher);
    }
    @FromXML
    public void but_1_1(View button){
        Toast.makeText(MainActivity.this, getString(R.string.but_1_1), Toast.LENGTH_SHORT).show();
        mFragmentManager = getSupportFragmentManager();
        FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
        xfragmentTransaction.replace(R.id.containerView, new Fragment1_1());
        xfragmentTransaction.addToBackStack(null).commit();
    }
}

tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical">
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:background="@color/l_orange"
        app:tabIndicatorColor="@color/orange"
        app:tabSelectedTextColor="@color/orange"
        app:tabTextColor="@color/grey"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>
</LinearLayout>

TabFragment.java
package com.s.MR;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment extends Fragment {
    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /** Inflate tab_layout и настройки для Views */
            View x =  inflater.inflate(R.layout.tab_layout,null);
            tabLayout = (TabLayout) x.findViewById(R.id.tabs);
            viewPager = (ViewPager) x.findViewById(R.id.viewPager);
        /** Устанавливаем Adpater для View Pager */
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        /** Костыль (временный?). Без него не работает setupWithViewPager. Возможно баг Support Library */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                    tabLayout.setupWithViewPager(viewPager);
                   }
        });
        return x;
    }
    class MyAdapter extends FragmentPagerAdapter{
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        /** Возвращаем fragment по отношению к Position */
        @Override
        public Fragment getItem(int position)
        {
          switch (position){
              case 0 : return new Fragment1();
              case 1 : return new Fragment2();
              case 2 : return new Fragment3();
          }
        return null;
        }
        @Override
        public int getCount() {
            return int_items;
        }
        /** Этот метод возвращает заголовок вкладки в соответствии с position */
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position){
                case 0 :
                    return getString(R.string.tab1);
                case 1 :
                    return getString(R.string.tab2);
                case 2 :
                    return getString(R.string.tab3);
            }
                return null;
        }
    }
}

frag_layout1.xml
<Button
        android:id="@+id/but_1_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/but_1_1"
        android:onClick="but_1_1"/>
</RelativeLayout>

In fact, it turns out:
1. There is "@+id/containerView"
in activity_main.xml 2. There is "@+id/viewPager"
in tab_layout.xml 3. In Main_Activity.java we do replace(R.id.containerView, new Fragment1_1( )); - everything turns out without problems. Those. fragment 1_1 is output.
But if in Main_Activity.java we do replace(R.id.viewPager, new Fragment1_1()); - Nothing happens. Why? How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Smolyakov, 2015-12-31
@spudro

And you know a lot about perversions!
https://youtu.be/ula2EDI1d_o

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question