如何在onClick Button上传递两个片段之间的参数

时间:2016-05-05 07:51:18

标签: android android-fragments android-studio android-viewpager

我有以下问题:当我点击按钮时,我想要从MyListFragment传递参数到FragmentTwo;但是我所拥有的代码并不起作用......我不知道为什么......我希望你能帮助我! 感谢

public class ScrollableTabsActivity extends AppCompatActivity {

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

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

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

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new MyListFragment(),"PIZZE");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new ThreeFragment(), "THREE");
        adapter.addFrag(new FourFragment(), "FOUR");
        adapter.addFrag(new FiveFragment(), "FIVE");
        adapter.addFrag(new SixFragment(), "SIX");
        adapter.addFrag(new SevenFragment(), "SEVEN");
        adapter.addFrag(new EightFragment(), "EIGHT");
        adapter.addFrag(new NineFragment(), "NINE");
        adapter.addFrag(new TenFragment(), "TEN");


        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 mFragmentTitleList.get(position);
        }
    }

}

MY FRAGMENT LIST:

public class MyListFragment extends Fragment implements
        android.widget.CompoundButton.OnCheckedChangeListener {

    ListView lv;
    ArrayList<Planet> planetList;
    PlanetAdapter plAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);
        Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            showResult(v);

            }
        });
        //return inflater.inflate(R.layout.fragment_list2, container, false);
        return  rootView;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();
    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", 6, "€"));
        planetList.add(new Planet("Diavola", 7,"€"));
        planetList.add(new Planet("Bufalina", 5,"€"));
        planetList.add(new Planet("Marinara", 5,"€"));
        planetList.add(new Planet("Viennese", 4,"€"));

        plAdapter = new PlanetAdapter(planetList, getContext()) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);


            /*Toast.makeText(
                getActivity(),
                "Clicked on Pizza: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };
        lv.setAdapter(plAdapter);
    }



    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        /*int pos = lv.getPositionForView(buttonView);
        if (pos != ListView.INVALID_POSITION) {
            Planet p = planetList.get(pos);
            p.setSelected(isChecked);


            *//*Toast.makeText(
                getActivity(),
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*//*
        }*/

    }


    public void showResult(View v) {
        String  result = "Selected Product are :";
        int totalAmount=0;
        String b="";

        for (Planet p : plAdapter.getBox()) {
            if (p.selected){

                result += "\n" + p.name+" "+p.distance+"€"+"q.tà :"+p.getQuantità();
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                totalAmount+=p.distance * quantitaInt;
                b=String.valueOf(totalAmount);


            }
        }
     // Toast.makeText(getActivity(), result + "\n" + "Total Amount:=" + totalAmount+"€", Toast.LENGTH_LONG).show();

        Fragment fragment = new Fragment();
        Bundle bundle = new Bundle();
        bundle.putString("totale", b);
        fragment.setArguments(bundle);







    }

}

FRAGMENT TWO:

public class TwoFragment extends Fragment{

    public TwoFragment() {
        // Required empty public constructor
    }

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

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

        TextView titolo2 = (TextView)rootView.findViewById(R.id.quantità2);
        Bundle bundle=getArguments();
        String myInt = bundle.getString("totale", null);
        titolo2.setText(myInt);

        return rootView;
    }

}

logcat的:

05-05 10:00:59.476 14753-14753/info.androidhive.materialtabs E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               java.lang.NullPointerException
                                                                                   at info.androidhive.materialtabs.fragments.TwoFragment.onCreateView(TwoFragment.java:32)
                                                                                   at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
                                                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                                   at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                                                                                   at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                                   at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
                                                                                   at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
                                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
                                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                                                   at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
                                                                                   at android.view.View.measure(View.java:12723)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
                                                                                   at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
                                                                                   at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
                                                                                   at android.view.View.measure(View.java:12723)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
                                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
                                                                                   at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                   at android.view.View.measure(View.java:12723)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
                                                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
                                                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
                                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
                                                                                   at android.view.View.measure(View.java:12723)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
                                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
                                                                                   at android.view.View.measure(View.java:12723)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
                                                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
                                                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
                                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
                                                                                   at android.view.View.measure(View.java:12723)
                                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
                                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
                                                                                   at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2092)
                                                                                   at android.view.View.measure(View.java:12723)
                                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1064)
                                                                                   at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                   at android.os.Looper.loop(Looper.java:137)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:4424)
                                                                                   at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
                                                                                   at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

试试这个!!!

public class TwoFragment extends Fragment{

public TwoFragment() {
    // Required empty public constructor
}

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

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

    TextView titolo2 = (TextView)rootView.findViewById(R.id.quantità2);
    Bundle bundle=getArguments();
  if(bundle != null){
  String myInt = bundle.getString("totale", null);
    titolo2.setText(myInt);
  }


    return rootView;
}

}

OneFragment

public void showResult(View v) {
    String  result = "Selected Product are :";
    int totalAmount=0;
    String b="";

    for (Planet p : plAdapter.getBox()) {
        if (p.selected){

            result += "\n" + p.name+" "+p.distance+"€"+"q.tà :"+p.getQuantità();
            int quantitaInt= Integer.parseInt(p.getQuantità() );
            totalAmount+=p.distance * quantitaInt;
            b=String.valueOf(totalAmount);


        }
    }
 // Toast.makeText(getActivity(), result + "\n" + "Total Amount:=" + totalAmount+"€", Toast.LENGTH_LONG).show();

    Bundle bun = new Bundle();
    bun.putString("totale", b);
    TwoFragment fgsearch = new TwoFragment();
    fgsearch.setArguments(bun);
    android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content_main, fgsearch);
    transaction.commit();

}

当replace fragment将FrameLayout更改为two_fragment.xml

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



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


</LinearLayout>

答案 1 :(得分:0)

我认为您的问题在线指出

 TextView titolo2 = (TextView)rootView.findViewById(R.id.quantità2);
    Bundle bundle=getArguments();
  String myInt = bundle.getString("totale", null);<---- here remove the null  
    //argument do it like this below
    String myInt = bundle.getString("totale")
    titolo2.setText(myInt);