在Viewpager上更改片段

时间:2017-08-23 10:15:22

标签: android android-fragments android-viewpager

在viewpager适配器中成功将我的LoginFragment更改为RegisterFragment,但未在RegisterFragment中显示任何视图。

我想创建tablayout活动,其中2片段: 1. LoginFragment 2. ProductFragment

但是当LoginFragment打开时,会有一个注册按钮。当用户单击Register Button替换或将LoginFragment更改为RegisterFragment时。用户单击时,RegisterFragment有一个登录按钮登录按钮将RegisterFragment替换为LoginFragment。在我的代码中,当我单击注册按钮时,它显示空视图,我无法显示我的RegisterFragment视图,如Button,TextView等。

MainActivity.class


package com.zxdmjr.testapplication;

import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.zxdmjr.testapplication.adapters.PagerAdapter;
import com.zxdmjr.testapplication.fragments.LoginFragment;
import com.zxdmjr.testapplication.fragments.RegisterFragment;

public class MainActivity extends AppCompatActivity {


    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;
    private PagerAdapter adapter;

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

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


        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        //mViewPager.setAdapter();
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        tabLayout.addTab(tabLayout.newTab().setText("Login").setTag("LoginFragment"));
        tabLayout.addTab(tabLayout.newTab().setText("Product").setTag("ProductFragment"));

        FragmentManager fragmentManager = getSupportFragmentManager();
        adapter = new PagerAdapter(fragmentManager, tabLayout.getTabCount());
        mViewPager.setAdapter(adapter);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    }

    @Override
    public void onBackPressed() {
        if(mViewPager.getCurrentItem() == 0) {
            if (adapter.getItem(0) instanceof RegisterFragment) {
                ((RegisterFragment) adapter.getItem(0)).backPressed();
            }
            else if (adapter.getItem(0) instanceof LoginFragment) {
                finish();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}


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:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.zxdmjr.testapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <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/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:layout_below="@+id/appbar"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</RelativeLayout>

LoginFragment.class


package com.zxdmjr.testapplication.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.zxdmjr.testapplication.R;
import com.zxdmjr.testapplication.interfaces.OnFragmentChangeListener;

/**
 * Created by eict on 8/23/17.
 */

public class LoginFragment extends Fragment implements OnFragmentChangeListener{


    private OnFragmentChangeListener onFragmentChangeListener;

    private Button btnRegister;

    public LoginFragment(){

    }

    public static LoginFragment newInstance(OnFragmentChangeListener listener){

        LoginFragment loginFragment = new LoginFragment();
        loginFragment.onFragmentChangeListener = listener;
        return loginFragment;

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);


        btnRegister = (Button) view.findViewById(R.id.btn_register);

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onFragmentChangeListener.onNext();
            }
        });

        return view;

    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onNext() {

    }
}

fragment_login.xml

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

    <Button
        android:id="@+id/btn_register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="88dp" />
</RelativeLayout>

RegisterFragment.class


package com.zxdmjr.testapplication.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.zxdmjr.testapplication.R;
import com.zxdmjr.testapplication.interfaces.OnFragmentChangeListener;

/**
 * Created by eict on 8/23/17.
 */

public class RegisterFragment extends Fragment implements OnFragmentChangeListener{

    private OnFragmentChangeListener onFragmentChangeListener;

    private Button btnLogin;

    public RegisterFragment(){

    }

    public static RegisterFragment newInstance(OnFragmentChangeListener listener){

        RegisterFragment registerFragment = new RegisterFragment();
        registerFragment.onFragmentChangeListener = listener;
        Log.d("RegisterFragment", "newInstance: Register");
        return registerFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_register, container, false);


        Log.d("RegisterFragment", "onCreateView: RegisterFragment");

        btnLogin = (Button) view.findViewById(R.id.btn_login);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onFragmentChangeListener.onNext();
            }
        });


        return view;

    }

    @Override
    public void onPause() {
        super.onPause();

    }

    public void backPressed() {
        onFragmentChangeListener.onNext();
    }

    @Override
    public void onNext() {

    }
}


fragment_register.xml

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

    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="208dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="58dp"
        android:text="TextView"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/btn_login"
        android:layout_alignStart="@+id/btn_login" />
</RelativeLayout>


PagerAdapter.class


package com.zxdmjr.testapplication.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

import com.zxdmjr.testapplication.fragments.LoginFragment;
import com.zxdmjr.testapplication.fragments.ProductFragment;
import com.zxdmjr.testapplication.fragments.RegisterFragment;
import com.zxdmjr.testapplication.interfaces.OnFragmentChangeListener;

/**
 * Created by eict on 8/23/17.
 */

public class PagerAdapter extends FragmentPagerAdapter {

    private FragmentManager manager;
    private Fragment fragment;
    private int numOfFrag;

    private final FragmentChange listener = new FragmentChange();

    private final class FragmentChange implements
            OnFragmentChangeListener{
        @Override
        public void onNext() {
            manager.beginTransaction().remove(fragment)
                    .commit();
            if (fragment instanceof LoginFragment){
                Log.d("RegisterFragment", "onNext: loginfragment");
                fragment = RegisterFragment.newInstance(listener);
            }else{ // Instance of NextFragment
                Log.d("RegisterFragment", "onNext: registerfragment");
                fragment = LoginFragment.newInstance(listener);
            }
            notifyDataSetChanged();
        }
    }


    public PagerAdapter(FragmentManager fm, int n) {
        super(fm);
        manager = fm;
        numOfFrag = n;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position){

            case 0:

                if(fragment == null){

                    fragment = LoginFragment.newInstance(listener);

                }

                return fragment;

            case 1:
                return ProductFragment.newInstance();

        }

        return null;

    }

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

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof LoginFragment && fragment instanceof RegisterFragment)
            return POSITION_NONE;
        else if(object instanceof RegisterFragment && fragment instanceof LoginFragment)
            return POSITION_NONE;

        return POSITION_UNCHANGED;
    }
}

0 个答案:

没有答案