Android Fragment替换onClick以及要更改的选定选项卡

时间:2016-09-19 20:21:17

标签: android android-fragments tabs

我有一个MainActivity,其AppBar包含工具栏和TabLayout,还有ViewPager

MainActivity拥有4个片段,包括家庭,现金,卡片和帐户。

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private AppBarLayout appBarLayout;
    Window window;

    @Override
    @SuppressWarnings("deprecation")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        window = this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(this.getResources().getColor(R.color.color_primary_green_dark));
        }

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setTitle("Example Wallet");
        toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
        appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Toast.makeText(getBaseContext(), "Tab " + position + " Onpage Selected " + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show();
                if (position == 0) {
                    appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
                    tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
                    }
                } else if (position == 1) {
                    appBarLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    tabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
                    }
                } else if (position == 2) {
                    appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow));
                    tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow_dark));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        window.setStatusBarColor(getResources().getColor(R.color.color_primary_yellow_dark));
                    }
                } else if (position == 3) {
                    appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red));
                    tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red_dark));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        window.setStatusBarColor(getResources().getColor(R.color.color_primary_red_dark));
                    }
                } else {
                    appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
                    tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab);
        if (fab1 != null) {
            fab1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent registerIntent = new Intent(MainActivity.this, Detail.class);
                    startActivity(registerIntent);
                }

            });
        }
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new FragmentMain(), "Home");
        adapter.addFrag(new FragmentCash(), "Cash");
        adapter.addFrag(new FragmentCard(), "Card");
        adapter.addFrag(new FragmentAccount(), "Account");
        adapter.addFrag(PartThreeFragment.createInstance(20), "Tab1");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {

            // return null to display only the icon
            return mFragmentTitleList.get(position);
        }
    }
}

家庭片段代码

public class FragmentMain extends Fragment {
    private List<Movie> movieList1 = new ArrayList<>();
    private List<Movie> movieList2 = new ArrayList<>();
    private RecyclerView recyclerView,recyclerView1;
    private MovieAdapter mAdapter1,mAdapter2;
    private LinearLayout cash_layout,card_layout,account_layout;
    private ViewGroup c;

    public FragmentMain() {

    }

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v= inflater.inflate(R.layout.content_main, container, false);
        //final android.app.ActionBar actionBar = getActivity().getActionBar();
        //c=container;
        recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
        cash_layout = (LinearLayout) v.findViewById(R.id.linearLayout_cash_bal);
        card_layout = (LinearLayout) v.findViewById(R.id.linearLayout_card_bal);
        account_layout = (LinearLayout) v.findViewById(R.id.linearLayout_account_bal);

        mAdapter1 = new MovieAdapter(movieList1);
        RecyclerView.LayoutManager mLayoutManager1 = new LinearLayoutManager(v.getContext());
        recyclerView.setLayoutManager(mLayoutManager1);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter1);
        prepareMovieData1();

        cash_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            @SuppressWarnings("deprecation")
            public void onClick(View v) {
                getContext().getActionBar().setSelectedNavigationItem(2);
                /*actionBar.selectTab(actionBar.getTabAt(1));
                FragmentManager fm=getFragmentManager();
                fm.beginTransaction().replace(R.layout.content_cash, (Fragment)new FragmentCash()).commit();
                getActivity().getActionBar().setTitle("Home");
                //ActionBar actionBar = getActivity().getActionBar();*/
                /*FragmentCash fragment2 = new FragmentCash();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragment_container,fragment2);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();*/
            }
        });

        /*mAdapter2 = new MovieAdapter(movieList2);
        RecyclerView.LayoutManager mLayoutManager2 = new LinearLayoutManager(v.getContext());
        recyclerView1.setLayoutManager(mLayoutManager2);
        recyclerView1.setItemAnimator(new DefaultItemAnimator());
        recyclerView1.setAdapter(mAdapter2);
        prepareMovieData2();*/
        return v;
    }

    private void prepareMovieData1() {
        movieList1.clear();
        Movie movie = new Movie("info","List is empty", "To create an item, click on (+) button", "","");
        movieList1.add(movie);
        mAdapter1.notifyDataSetChanged();
    }

    /*public void onClick1(View v) {
        FragmentCash fragment2 = new FragmentCash();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(android.R.id.content,fragment2);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }*/

    /*private void prepareMovieData2() {
        Movie movie = new Movie("card","Card", "New Dress", "Rs.50.00","11/09/2016");
        movieList2.add(movie);
        mAdapter2.notifyDataSetChanged();
    }*/
}

我正在尝试从家庭片段调用现金,卡和帐户片段,但此代码

cash_layout.setOnClickListener(new View.OnClickListener() {
    @Override
    @SuppressWarnings("deprecation")
    public void onClick(View v) {
        FragmentCash fragment2 = new FragmentCash();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container,fragment2);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
});

添加其他片段,主片段可见。

我需要的解决方案是,在下图中,当我点击现金余额时,它会滑动到现金选项卡上,并在屏幕上显示现金片段。

screenshot

1 个答案:

答案 0 :(得分:0)

看起来您正在尝试在视图寻呼机顶部添加现金片段,或者将它们全部替换掉​​。我假设你想在viewPager中导航到它,而不是在当前视图中替换它。

为此,请使用pager.setCurrentItem(//Page number with cash fragment on it)

替换所有onClick代码

所以,你的onClick看起来像这样:

cash_layout.setOnClickListener(new View.OnClickListener() {
        @Override
        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            ((MainActivity) getActivity()).getViewPager().setCurrentItem(//Your desired page number as int);
        }
    });

或者你可以通过界面轻松解决这个问题。

只需创建一个界面即可访问您的viewPager操作。

public interface ViewPagerInterface {
    ViewPager getViewPager();
}

让您的活动实施它:

public MainActivity extends AppCompatActvity implements ViewPagerInterface {

    @Override
    public ViewPager getViewPager() {
        return this.viewPager;
    }
}

然后将该接口传递给Fragments并调用getViewPager方法。

viewPagerInterface.getViewPager().setCurrentItem(<my-int>);