简体   繁体   中英

Passing a data from Activity to Tabbed Layout Fragment?

I have two Activities. One is normal Activity which contains listview and second one is Tabbed Layout which it have two tabs. One is "Description" tab and another one is "Sample Code" tab.

I have created two seperate fragments for each namely "OneFragment" and "TwoFragment". All i need is when user click an Item from my normal Activity, this item will be stored in string and that string should be passed to Tabbed layout and it should be showed in OneFragment ie., "Description" tab

(Ex). My List Contains {"Android","Studio"} if user clicks Android,this text should pass to description tab and showed the text using TextView. please help me. Here i include my respective codes..

NormalActivity - >ListActi.java

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        lv = (ListView) findViewById(R.id.listView);
        final List<String> ListElementsArrayList = new ArrayList<String>(Arrays.asList(listElements));
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (getApplicationContext(), android.R.layout.simple_list_item_1, ListElementsArrayList);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(getApplicationContext(), listElements[position],Toast.LENGTH_LONG).show();
                s = listElements[position];
                if(position == 1){
                    s = listElements[position];
                    Bundle bundle = new Bundle();
                    bundle.putString("ClickedItem", listElements[position]);
                    OneFragment fragobj = new OneFragment();
                    TwoFragment fag = new TwoFragment();
                    fragobj.setArguments(bundle);
                    fag.setArguments(bundle);
                    Intent i = new Intent(getApplicationContext(),BothLay.class);
                    startActivity(i);
                }
           }
        });
    }
}

TabActivity - > BothLay

public class BothLay extends AppCompatActivity  {
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_both_lay);
        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.addFragment(new OneFragment(), "Description");
        adapter.addFragment(new TwoFragment(), "Sample Code");
        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);
        }
    }
}

Decription tab - >OneFragment (All i need is pass a data from Normal Activity to this Fragment)

public class OneFragment extends Fragment{
    String strtext = "Ajay";
    public OneFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootview = inflater.inflate(R.layout.fragment_one, container, false);
        TextView textView = (TextView) rootview.findViewById(R.id.t1);
        //strtext = getIntent().getStringExtra("ClickedItem"); //this doesn't work  
        textView.setText(strtext);
        return rootview;
    }
}

Sample Code tab ->Twofragment

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) {
        return inflater.inflate(R.layout.fragment_two, container, false);
    }

}

Here:

fragobj.setArguments(bundle);
fag.setArguments(bundle);

Not work on click of Button because currently starting BothLay Activity instead of adding Fragment to FragmentManager .

To get it work:

1. Pass bundle using Intent to BothLay Acivity on Click of Button:

  Intent i = new Intent(getApplicationContext(),BothLay.class);
  i.putExtras(bundle);
  startActivity(i);

2. Get Bundle from Intent in onCreate of BothLay Activity then pass it to Fragment's when calling adapter.addFragment method:

  Bundle bundle = getIntent().getExtras();
  tabLayout.setupWithViewPager(viewPager,bundle);

Pass bundle to Fragment objects:

   private void setupViewPager(ViewPager viewPager,Bundle bundle) {
        ...
        Fragment fragmentOne=new OneFragment();
        fragmentOne.setArguments(bundle);
        adapter.addFragment(fragmentOne, "Description");
        // do same for second Framgment
   }

EDIT:

To get data in Fragment call getArguments method in onCreateView of Fragment:

Bundle bundle=getArguments();
if(bundle!=null){
  if(bundle.containsKey("ClickedItem")){
     String strClickedItem=bundle.getString("ClickedItem");
   }
}

Do all steps which i provide the link.

And the 4th step need to be implemented when your fragment is resumed.

below code will be in your activity,

SelectedBundle selectedBundle;

finally you will get the instance of fragment on selectedBundle.

so, you can easily pass the value to the fragment. Like,

  fragment.setData(String passedData);

that's all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM