如何使用view pager在android片段选项卡中移动下一页?

时间:2014-12-12 05:59:48

标签: android android-fragments

我有两个tabs.Login和Register片段。我在登录选项卡中单击了注册按钮,当我单击时,它应该移动到注册片段 我在LoginActivity中使用了这个方法

public void setCurrentItem(int item, boolean smoothScroll) {
    mPager.setCurrentItem(item, smoothScroll);
}

我在Login片段中获取该方法但显示错误 我的代码如下:

public class LoginActivity extends SherlockFragmentActivity {

    private ViewPager mPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from activity_main.xml
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.loginpager);
        PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        tabs.setIndicatorColor(Color.BLUE);
        tabs.setIndicatorHeight(5);
        mPager = (ViewPager) findViewById(R.id.pager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(fm);
        mPager.setAdapter(adapter);
        tabs.setViewPager(mPager);

    }

    public void setCurrentItem(int item, boolean smoothScroll) {
        mPager.setCurrentItem(item, smoothScroll);
    }

    public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(android.support.v4.app.FragmentManager fm) {
            super(fm);
        }

        private final String[] TITLES = { "LOG IN", "REGISTER" };

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public SherlockFragment getItem(int arg0) {
            switch (arg0) {
            // Open LoginFragment
            case 0:
                LoginFragment loginfragment = new LoginFragment();
                return loginfragment;

            // Open RegisterFragment
            case 1:
                RegisterFragment registerfragment= new RegisterFragment();
                return registerfragment;

            }
        return null;
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

    } 
}

LoginFragment:

public class LoginFragment extends SherlockFragment implements OnClickListener {

    private LoginActivity loginActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Get the view from fragmenttab3.xml
        View view = inflater.inflate(R.layout.login, container, false);
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new ForegroundColorSpan(Color.BLACK), 24, 32, 0);
        ClickableSpan clickableSpan = new SpaceAdjust(text) {
            @Override
            public void onClick(View textView) {
                loginActivity = new LoginActivity();
                loginActivity.setCurrentItem(2, true); // here i am getting error. How to swipe to RegisterFragment
            }
        };
        spannableString.setSpan(clickableSpan, 24, 32, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        dontHaveAccountRegister.setText(spannableString);
        dontHaveAccountRegister.setMovementMethod(LinkMovementMethod.getInstance());
        return view;
    }
}

错误:

12-12 00:41:53.906: E/AndroidRuntime(1580): FATAL EXCEPTION: main
12-12 00:41:53.906: E/AndroidRuntime(1580): Process: com.a.b, PID: 1580
12-12 00:41:53.906: E/AndroidRuntime(1580): java.lang.NullPointerException
12-12 00:41:53.906: E/AndroidRuntime(1580):     at com.a.b.LoginActivity.setCurrentItem(LoginActivity.java:148)
12-12 00:41:53.906: E/AndroidRuntime(1580):     at com.a.b.views.LoginFragment$5.onClick(LoginFragment.java:250)
12-12 00:41:53.906: E/AndroidRuntime(1580):     at android.text.method.LinkMovementMethod.onTouchEvent(LinkMovementMethod.java:217)
12-12 00:41:53.906: E/AndroidRuntime(1580):     at android.widget.TextView.onTouchEvent(TextView.java:7724)
12-12 00:41:53.906: E/AndroidRuntime(1580):     at android.view.View.dispatchTouchEvent(View.java:7690)
12-12 00:41:53.906: E/AndroidRuntime(1580):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
12-12 00:41:53.906: E/AndroidRuntime(1580):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
12-12 00:41:53.906: E/AndroidRuntime(1580):     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)

2 个答案:

答案 0 :(得分:3)

试试这个工作正常

创建布局文件login_layout.xml

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

<Button
    android:id="@+id/register_btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="@string/register_here" />

</RelativeLayout>

创建布局文件register_layout.xml

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

<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="@string/register_layout" />

</RelativeLayout>

为tabhost fragment_home.xml

创建布局
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ts="http://schemas.android.com/apk/res-auto"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fadingEdge="none"
        android:background="#394c58"
        android:tabStripEnabled="false" />

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
</LinearLayout>

</TabHost>

更改您的主要活动文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >  

      <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />
</android.support.v4.widget.DrawerLayout>

创建一个类文件LoginFragment.java

package com.example.tabfragment;

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

public class LoginFragment extends Fragment {

ViewPager viewPager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.login_layout, null);

    Button registerButton = (Button) rootView
            .findViewById(R.id.register_btn);
    registerButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            viewPager = (ViewPager) getActivity().findViewById(
                    R.id.viewpager);
            viewPager.setCurrentItem(1);

        }
    });
    return rootView;
}
}

创建一个类文件RegisterFragment.java

package com.example.tabfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class RegisterFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.register_layout, null);
    return rootView;
}

}

创建一个类文件TabFragments.java

package com.example.tabfragment;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;


public class TabFragments extends Fragment implements OnPageChangeListener,
    OnTabChangeListener {

public static final int TAB_LOGIN = 0;
public static final int TAB_REG = 1;

private TabHost tabHost;
private int currentTab = TAB_LOGIN;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, null);
    tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
    viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
    viewPager.setOnPageChangeListener(this);
    fragments = new ArrayList<Fragment>();
    fragments.add(new LoginFragment());
    fragments.add(new RegisterFragment());

    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
    pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
            fragments, getArguments());
    pageAdapter.notifyDataSetChanged();
    viewPager.setAdapter(pageAdapter);
    setupTabs();

}

private void setupTabs() {
    tabHost.setup();
    tabHost.addTab(newTab(R.string.login));
    tabHost.addTab(newTab(R.string.register));
    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {

        tabHost.getTabWidget().getChildAt(i)
                .setBackgroundColor(Color.parseColor("#304c58"));

        // tabHost.setBackgroundResource(R.drawable.tab_selector);
        final View view = tabHost.getTabWidget().getChildTabViewAt(i);
        final View textView = view.findViewById(android.R.id.title);
        ((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));

        ((TextView) textView).setSingleLine(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            tabHost.getTabWidget().getChildAt(i)
                    .findViewById(android.R.id.icon);
            tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;

        } else {

            if (view != null) {
                // reduce height of the tab
                view.getLayoutParams().height *= 0.77;

                if (textView instanceof TextView) {
                    ((TextView) textView).setGravity(Gravity.CENTER);
                    textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                    textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
            }
        }

    }
    tabHost.setOnTabChangedListener(TabFragments.this);
    tabHost.setCurrentTab(currentTab);
}

private TabSpec newTab(int titleId) {
    TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
    tabSpec.setIndicator(getString(titleId));
    tabSpec.setContent(new TabFactory(getActivity()));
    return tabSpec;
}

@Override
public void onPageScrollStateChanged(int position) {

}

@Override
public void onPageScrolled(int position, float arg1, int arg2) {

}

@Override
public void onPageSelected(int position) {
    tabHost.setCurrentTab(position);
}

@Override
public void onTabChanged(String tabId) {
    currentTab = tabHost.getCurrentTab();
    viewPager.setCurrentItem(currentTab);
    updateTab();
}

@SuppressWarnings("unused")
private void updateTab() {
    switch (currentTab) {
    case TAB_LOGIN:
        LoginFragment login = (LoginFragment) fragments.get(currentTab);
        break;
    case TAB_REG:
        RegisterFragment register = (RegisterFragment) fragments
                .get(currentTab);
        break;
    }
}

class TabFactory implements TabContentFactory {

    private final Context context;

    public TabFactory(Context context) {
        this.context = context;
    }

    @Override
    public View createTabContent(String tag) {
        View v = new View(context);
        v.setMinimumHeight(0);
        v.setMinimumWidth(0);
        return v;
    }

}
}

创建一个类文件TabFragmentPageAdapter .java

import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;

public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments,
        Bundle args) {
    super(fm);
    this.fragments = fragments;
    this.args = args;
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = fragments.get(position);
    fragment.setArguments(args);
    return fragment;
}

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

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}
}

最终改变你的mainactivity.java类

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {

Fragment fragment = null;

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

    fragment = new TabFragments();


    if (fragment != null) {
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.frame_container, fragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                .commit();
    }
    }

    }

答案 1 :(得分:0)

您不应该创建活动实例来访问其方法。它是 Fragment Parent Activity

所以你可以直接访问它:

((LoginActivity)getActivity()).setCurrentItem(2, true);

希望它有助于ツ