如何通过视图分页器将值从活动传递到片段

时间:2016-08-31 09:45:29

标签: android android-fragments android-viewpager

我有一个使用视图寻呼机在片段之间切换的活动。我有三个片段。在这些片段之间切换时,我必须将一个字符串值传递给片段类,以识别选择哪个片段。因为这里我对所有三个片段使用相同的片段类。 这是我的主要活动。

public class mainActivity extends AppCompatActivity {

public String kind, value;
private TabLayout tabLayout;
private ViewPager viewPager;
public FloatingActionButton upload, send;

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
  upload = (FloatingActionButton) findViewById(R.id.upload_fab);
    send = (FloatingActionButton) findViewById(R.id.send_message);
    uploadFab.hide();

    Intent mIntent = getIntent();
     kind = mIntent.getStringExtra("KIND");

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

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


    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            Student student =new Student();
            switch (position) {
                case 0:

                    upload.hide();
                    value = "r";

                    break;

                case 1:
                    upload.hide();
                    value = "e";
                    break;

                case 2:
                    upload.show();
                    value = "u";
                    break;

                default:
                    upload.hide();
                    val = "r";
                   break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

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

    adapter.addFragment(new RemainderFragment(), "REMAINDER");
    adapter.addFragment(new RemainderFragment(), "EMAIL");
    adapter.addFragment(new RemainderFragment(), "UPLOAD");
    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);
    }
   }

这是我的片段类

public class RemainderFragment extends Fragment {
   public RemainderEmailFragment() {
    // 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
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);

EditText  subject = (EditText) rootView.findViewById(R.id.subject);
EditText des = (EditText) rootView.findViewById(R.id.description);
//  String value = mainActivity.value      
       //button to send data

    button = activity.send;
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //getting details
            SendData();


         }
    });

    return rootView;
 }


public void SendData() {
    //functon

 }

我尝试过Intent和共享首选项来发送数据。但没有任何效果。我必须在我的片段类中获取String值。请帮忙。

1 个答案:

答案 0 :(得分:0)

请检查以下代码以获取所需的示例更改,我已修改您的文件并添加了一些代码以支持您的要求。

您的活动文件

    package com.adobe.reader.test;

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

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;

    import com.adobe.reader.R;

    public class mainActivity extends AppCompatActivity
    {

        public String kind, value;
        private TabLayout            tabLayout;
        private ViewPager            viewPager;
        public  FloatingActionButton upload, send;

        // Adding adapter
        private ViewPagerAdapter adapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);
            upload = (FloatingActionButton) findViewById(R.id.upload_fab);
            send = (FloatingActionButton) findViewById(R.id.send_message);
            uploadFab.hide();

            Intent mIntent = getIntent();
            kind = mIntent.getStringExtra("KIND");

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

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


            // Let's say we need to call some method from fragment in the activity
            Fragment fragment = getCurrentFragment();
            if (Fragment instanceof RemainderFragment)
            {
                RemainderFragment remainderFragment = (RemainderFragment) fragment;
                remainderFragment.setString("Testing string");
            }

            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {

                   Fragment fragment = getCurrentFragment();
                   if (Fragment instanceof RemainderFragment)
                   {
                        RemainderFragment remainderFragment = (RemainderFragment) fragment;
                   }

                    Student student =new Student();
                    switch (position) {
                        case 0:

                            upload.hide();
                            value = "r";
                            break;

                        case 1:
                            upload.hide();
                            value = "e";
                            break;

                        case 2:
                            upload.show();
                            value = "u";
                            break;

                        default:
                            upload.hide();
                            val = "r";
                            break;
                    }
                    remainderFragment.setString(value);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

        }

        /**
         * This method will give you current fragment used in the viewpager.
         * @return
         */
        public Fragment getCurrentFragment()
        {
            Fragment fragment = null;
            if (viewPager != null)
            {
                int currentFragmentIndex = viewPager.getCurrentItem();

                if (adapter != null)
                {
                    fragment = adapter.getItem(currentFragmentIndex);
                }
            }
            return fragment;
        }


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

            adapter.addFragment(new RemainderFragment(), "REMAINDER");
            adapter.addFragment(new RemainderFragment(), "EMAIL");
            adapter.addFragment(new RemainderFragment(), "UPLOAD");
            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);
            }
        }

您的片段文件

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.adobe.reader.R;

public class RemainderFragment extends Fragment 
{
    public String testingString;

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

    // Sample method to be called from activity
    public void setString(String testStr)
    {
        testingString = testStr;
    }

    @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
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.raminder_fragment, container, false);

        EditText subject = (EditText) rootView.findViewById(R.id.subject);
        EditText des = (EditText) rootView.findViewById(R.id.description);
        //  String value = mainActivity.value      
        //button to send data

        button = activity.send;
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //getting details
                SendData();


            }
        });

        return rootView;
    }


    public void SendData() {
        //functon

    }