Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 460
Ajay Jayendran Avatar asked Dec 26 '16 05:12

Ajay Jayendran


People also ask

How can you pass data from an activity to a fragment?

So, to pass data from the MotherActivity to such a Fragment you will need to create private Strings/Bundles above the onCreate of your Mother activity - which you can fill with the data you want to pass to the fragments, and pass them on via a method created after the onCreate (here called getMyData()).

How do you pass data class between fragments?

To pass data between fragments in the same fragment manager, the listener should be added to the destination fragment with requestKey in order to receive the result produces from another fragment with the same key.

How do you pass data from second fragment to first fragment?

All you have to do is implement the correct type of listener, but the main point is shown. In one fragment activity, call a method and pass a variable to the main activity. From the main activity you can send it to your other fragment activity if you'd like. Save this answer.

How will you pass data from one fragment to another fragment in Android using interface?

To pass data from one fragment to another Bundle will help. LifeShapeDetailsFragment fragment = new LifeShapeDetailsFragment(); // object of next fragment Bundle bundle = new Bundle(); bundle. putInt("position", id); fragment. setArguments(bundle);


2 Answers

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");
   }
}
like image 167
ρяσѕρєя K Avatar answered Oct 01 '22 02:10

ρяσѕρєя K


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.

like image 32
Noorul Avatar answered Oct 01 '22 03:10

Noorul