Android 将值传递给ViewPager片段

Android 将值传递给ViewPager片段,android,android-fragments,android-intent,android-viewpager,android-bundle,Android,Android Fragments,Android Intent,Android Viewpager,Android Bundle,我想把dogruYanlis值传递给这些片段,它是一个整数数组。如果我尝试用bundle处理它,它会发送任何信息。我在fragment类中收到的数组始终为空。我想我不能处理bundle,但我不知道如何解决这个问题 我要发送数据的活动 package oztiryaki.my; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import

我想把dogruYanlis值传递给这些片段,它是一个整数数组。如果我尝试用bundle处理它,它会发送任何信息。我在fragment类中收到的数组始终为空。我想我不能处理bundle,但我不知道如何解决这个问题

我要发送数据的活动

package oztiryaki.my;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class result extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    private Bundle bundle;
    int[] dogruYanlis;

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

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        Bundle list = getIntent().getExtras();
        if(list == null){
            return;
        }
        dogruYanlis = list.getIntArray("dogruYanlis");

    }

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

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        bundle = new Bundle();
        bundle.putIntArray("dogruYanlis", dogruYanlis);

        result2015Fragment f15 = new result2015Fragment();
        f15.setArguments(bundle);

        result2014Fragment f14 = new result2014Fragment();
        f14.setArguments(bundle);

        result2013Fragment f13 = new result2013Fragment();
        f13.setArguments(bundle);

        adapter.addFragment(f15, "2015");
        adapter.addFragment(f14, "2014");
        adapter.addFragment(f13, "2013");
        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 addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

尝试使用Android studio提供的向导创建片段,该向导将为您提供一个虚拟的
片段
,其中包含传递数据所需的所有
片段
方法,例如:

package FRAGMENTS;

import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentLifecycleDemo extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String TEXT1 = "text1";
    private static final String TEXT2 = "text2";

    // the two strings are going to be used here
    private TextView title;
    private TextView subtitle;

    private String text1;
    private String text2;

    private Context c;

    private OnFragmentInteractionListener mListener;

    public FragmentLifecycleDemo(Context c) {
        // Required empty public constructor
        this.c = c;
    }

    public static FragmentLifecycleDemo newInstance(String title, String subtitle, Context c) {
        FragmentLifecycleDemo fragment = new FragmentLifecycleDemo(c);
        Bundle args = new Bundle();
        args.putString(TEXT1, title);
        args.putString(TEXT2, subtitle);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toast.makeText(c, "Hi! onCreate has just been called.", Toast.LENGTH_SHORT).show();
        if (getArguments() != null) {
            text1 = getArguments().getString(TEXT1);
            text2 = getArguments().getString(TEXT2);
        }
    }

    private void init(View v) {
        title = (TextView) v.findViewById(R.id.txtTry);
        title.setText(text1);

        subtitle = (TextView) v.findViewById(R.id.txtReal);
        subtitle.setText(text2);
    }

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

        View v = inflater.inflate(R.layout.fragment_lifecycle_demo, container, false);
        init(v);
        Toast.makeText(c, "Greetings from onCreateView!", Toast.LENGTH_SHORT).show();
        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        Toast.makeText(c, "Is it me, or a button has just been pressed?", Toast.LENGTH_SHORT).show();
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Toast.makeText(c, "Howdy! I've just been attached to the activity.", Toast.LENGTH_SHORT).show();
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Toast.makeText(c, "Oh no! I've been detached u.u", Toast.LENGTH_SHORT).show();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
包片段;
导入android.app.Fragment;
导入android.content.Context;
导入android.net.Uri;
导入android.os.Bundle;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.TextView;
导入android.widget.Toast;
公共类FragmentLifecycleDemo扩展了Fragment{
//片段初始化参数,例如ARG_ITEM_NUMBER
私有静态最终字符串TEXT1=“TEXT1”;
私有静态最终字符串TEXT2=“TEXT2”;
//这两个字符串将在这里使用
私有文本视图标题;
私有文本视图字幕;
私有字符串text1;
私有字符串text2;
私有上下文c;
私有OnFragmentInteractionListener mListener;
公共碎片LifecycleDemo(上下文c){
//必需的空公共构造函数
这个.c=c;
}
公共静态碎片LifecycleDemo newInstance(字符串标题、字符串副标题、上下文c){
FragmentLifecycleDemo片段=新的FragmentLifecycleDemo(c);
Bundle args=新Bundle();
args.putString(TEXT1,title);
args.putString(TEXT2,副标题);
fragment.setArguments(args);
返回片段;
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Toast.makeText(c,“嗨!刚刚调用了onCreate。”,Toast.LENGTH\u SHORT.show();
如果(getArguments()!=null){
text1=getArguments().getString(text1);
text2=getArguments().getString(text2);
}
}
私有void init(视图v){
title=(TextView)v.findviewbyd(R.id.txtry);
title.setText(text1);
副标题=(文本视图)v.findViewById(R.id.txtReal);
副标题.setText(text2);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图v=充气机。充气(R.layout.fragment\u lifecycle\u demo,container,false);
init(v);
Toast.makeText(c,“来自onCreateView的问候!”,Toast.LENGTH_SHORT.show();
返回v;
}
//TODO:重命名方法、更新参数并将方法挂接到UI事件中
public void onButtonPressed(Uri){
Toast.makeText(c,“是我吗,还是刚刚按下按钮?”,Toast.LENGTH\u SHORT.show();
if(mListener!=null){
onFragmentInteraction(uri);
}
}
@凌驾
公共void-onAttach(上下文){
super.onAttach(上下文);
Toast.makeText(c,“你好!我刚刚加入了活动。”,Toast.LENGTH\u SHORT.show();
if(OnFragmentInteractionListener的上下文实例){
mListener=(OnFragmentInteractionListener)上下文;
}否则{
抛出新的RuntimeException(context.toString()
+“必须实现OnFragmentInteractionListener”);
}
}
@凌驾
公共无效连接(){
super.onDetach();
Toast.makeText(c,“哦,不!我被分离了”,Toast.LENGTH\u SHORT.show();
mListener=null;
}
/**
*此接口必须由包含以下内容的活动实现
*片段,以允许通信此片段中的交互
*该活动以及其中可能包含的其他片段
*活动。
*

*有关更多信息,请参阅Android培训课程。 */ FragmentInteractionListener上的公共接口{ //TODO:更新参数类型和名称 void onFragmentInteraction(Uri); } }


如您所见,您应该从中获取
捆绑包的方法是
onCreate
方法,它接收从名为
newInstance
的构造函数发送的
片段上可用的数据

我也经历过类似的挣扎,也许这会有所帮助。如果活动中的变量在创建后没有改变,有一种简单的方法可以从活动创建的片段中找到活动的变量:

  • 获取片段中的上下文
  • 然后可以从片段中获取变量的值

    Context context;
    
    public void onViewCreated(View v, Bundle savedInstanceState) {
        context = getActivity();
        int i = ((result)context).dogruYanlis[0];
    }
    

  • 我像你说的那样更改代码,但现在它抛出java.lang.NullPointerException。我试图在onCreate方法中获取变量的值,对吗?好吧,我从片段的onViewCreated方法中获取变量,但我认为这不是问题所在。不要忘记在片段的开头声明上下文变量,在所有方法之外。是的,兄弟,我不会忘记,我在片段的开头声明它:(我做了一些编辑,请尝试这种方式。另外,您是否检查了活动列表中是否有元素?尝试记录它们以查看是否有。它会在什么上抛出NPE?并从fragment的onCreateView方法中删除所有与数组相关的代码,以便只保留视图膨胀、textview和return部分。)。
    Context context;
    
    public void onViewCreated(View v, Bundle savedInstanceState) {
        context = getActivity();
        int i = ((result)context).dogruYanlis[0];
    }