将值传递给ViewPager片段

时间:2016-02-23 21:38:27

标签: android android-fragments android-intent android-viewpager android-bundle

我想将dogruYanlis值传递给这些片段,这是一个整数数组。如果我尝试用捆绑它处理它,它会发送任何东西。我在fragment类中收到的数组总是为null。我认为我无法处理捆绑但我不知道如何解决这个问题......

我想要发送数据的活动

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);
        }
    }
}

片段活动之一

package oztiryaki.my;

        import android.os.Bundle;
        import android.support.annotation.Nullable;
        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.TextView;
        import android.widget.Toast;

/**
 * Created by oztir on 21.02.2016.
 */
public class result2015Fragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.result2015,container,false);
        int[] dogruYanlis = getArguments().getIntArray("dogruYanlis");
        if(dogruYanlis == null){
            Toast.makeText(getActivity(),"null sory:(", Toast.LENGTH_LONG).show();
        }
        TextView ygs1hp = (TextView) v.findViewById(R.id.ygs1hp);

        return v;
    }
    public void getArray(int[] dogruYanlis){
        Toast.makeText(getActivity(),Integer.toString(dogruYanlis[0]), Toast.LENGTH_LONG).show();
    }
}

2 个答案:

答案 0 :(得分:1)

尝试使用Android工作室提供的向导创建片段,这会为您提供一个虚拟Fragment,其中包含传递数据所需的所有Fragment方法,以及:

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);
    }
}

正如您所看到的,您应该获得Bundle的方法是onCreate,它接收您希望在Fragment上可用的数据,该数据是从newInstance发送的名为unix> gcc -c addvec.c multvec.c unix> ar rcs libvector.a addvec.o multvec.o 的构造函数。

答案 1 :(得分:1)

我有类似的斗争,也许这会有所帮助。如果活动中的变量在创建后没有变化,有一种简单的方法可以从它创建的片段中获取活动的变量:

  1. 获取片段中的上下文
  2. 然后你可以从片段中获取变量的值

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