pass explicit intent from ViewPagerAdapter to fragment - java

I have a viewpager with two tabs, and a fragment for each. How do i send an intent string extra to say FragmentMathematics()? This isnt as straight forward as creating an intent with a putExtra and then calling strartActivity().
Here is my simple class.
public class StartActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private String check;
private PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout404);
tabLayout.addTab(tabLayout.newTab().setText("Mathematics"));
tabLayout.addTab(tabLayout.newTab().setText("Physics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
Intent intent = getIntent();
check = intent.getStringExtra("SELECTVALUE");
if("Mathematics".equalsIgnoreCase(check)){
selectPage(1);
} else {
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
void selectPage(int pageIndex){
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
Thank you!

Use Bundle to pass data to fragment.
Bundle bundle = new Bundle();
bundle.putString("edttext", "Your Value");
// set Fragmentclass Arguments
FragmentMathematics fragobj = new FragmentMathematics();
fragobj.setArguments(bundle);
And In fragment OnCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String strtext = getArguments().getString("edttext");
}

Related

Set Text of EditeText of Fragment from Activity

How can I set the text of an EditText of an Fragment from the Activity?
Here es the Activity code:
public class MainActivity extends AppCompatActivity
{
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
// Create a new Tab named "First"
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Personal"); // set the Text for the first Tab
tabLayout.addTab(firstTab); // add the tab at in the TabLayout
// Create a new Tab named "Second"
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Chat"); // set the Text for the second Tab
tabLayout.addTab(secondTab); // add the tab in the TabLayout
try {
Fragment fragment = null;
fragment = new FirstFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
catch (Exception e) {
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
try {
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
catch (Exception e) {
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void connect(){
//set text of EditText of SecondFragment
}
}
I am looking for a solution to this problem:
I want to create a chat client and for that I need to update the EditText of a tab from time to time without the need to switch to that tab. I also need the content of that EditText not to be lost when switching tabs.
Just create a variable inside the main activity that you can update from the fragments. Since the activity's lifecycle doesn't change from one fragment to the other, you can then get the same value from the second fragment.
I hope this helps.
Assuming you don't want to use a ViewPager and a PagerAdapter (you don't need swiping between your tabs), this is what it should look like:
public class MainActivity extends AppCompatActivity
{
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
EditText editText;
FirstFragment firstFragment;
SecondFragment secondFragment;
private int selectedTabIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
simpleFrameLayout = findViewById(R.id.simpleFrameLayout);
tabLayout = findViewById(R.id.simpleTabLayout);
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Personal");
tabLayout.addTab(firstTab);
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Chat");
tabLayout.addTab(secondTab);
FragmentManager fm = getSupportFragmentManager();
if (savedInstanceState == null) {
firstFragment = new FirstFragment();
secondFragment = new SecondFragment();
fm.beginTransaction()
.add(R.id.simpleFrameLayout, firstFragment, "firstFragment")
.add(R.id.simpleFrameLayout, secondFragment, "secondFragment");
.detach(secondFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
.commitNow();
} else {
firstFragment = (FirstFragment) fm.findFragmentByTag("firstFragment");
secondFragment = (SecondFragment) fm.findFragmentByTag("secondFragment");
this.selectedTabIndex = savedInstanceState.getInt("selectedTabIndex", 0);
// selectTab(selectedTabIndex); // you don't need this line
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
this.selectedTabIndex = tab.getPosition();
selectTab(selectedTabIndex);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void selectTab(int selectedTabIndex) {
FragmentManager fm = getSupportFragmentManager();
if (selectedTabIndex == 0) {
fm.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.detach(secondFragment)
.attach(firstFragment)
.commitAllowingStateLoss();
} else if(selectedTabIndex == 1) {
fm.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.detach(firstFragment)
.attach(secondFragment)
.commitAllowingStateLoss();
}
}
public void connect(){
secondFragment.updateText("someText"); // this can run when secondFragment has no view!
}
}
Note: if you need to use more tabs, then you could use an array, but you'd still need to initialize / reinitialize as it is shown in this snippet.
A general answer based on your general question Make your edittext public static public static EditText editText;
Assign a value to it then call it like MainActivity.editText.setText(""); from any other class
`
Use this approach only if its absolutely necessary as it may lead to memory leaks since you will have to manually destroy/nullify your object after use

Change tab view with button

super new to coding. I followed a tutorial on creating tabs and fragments. My app right now has 3 tabs on the toolbar, and when clicked they change to their respective layout. I'd like to now add a button that will take me to those layouts instead of using the toolbar, so I can move it around and place it where I want.
This is what I have in my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
//Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Main2Activity(), "TAB1");
adapter.addFragment(new Main3Activity(), "TAB2");
adapter.addFragment(new Main4Activity(), "TAB3");
viewPager.setAdapter(adapter);
}
So then I added this code for the button. In my XML, I placed the button above the container id so that I can always see it. Ideally, I'd have 3 buttons, each one putting into the container id Main2Activity, Main3Activity, and Main4Activity. Here is just 1 button as I try to figure out how to get the view to change.
public void onClickBtn1(View v){
FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, new Main2Activity());
ft.commit();
}
This is also my SectionsPageAdapter page if it helps.
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
Thanks in advance!
Call ViewPager#setCurrentItem in your on click to go to the index of the item in the viewpager's adapter's list/array:
public void onClickBtn1(View v){
int gotoIndex = 0;
mViewPager.setCurrentItem(gotoIndex, /*smoothscrolling*/ true);
}

Do we need more than one Pager(viewpager) class, if we want to add tabs in more than one activity?

I have to make project which consist of 3 Activities. 1st and 2nd activity consist of 2 Tabs while 3rd activity needs 3 tabs. Do i need to make 3 Pager clases for each activity? Or if One Pager.class can handle all tabs then how we can sequence it??
Thanks to all In Advance!
You can use same PagerAdapter class. Below is an sample PagerAdapter.
TabsPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class TabsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public TabsPagerAdapter(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);
}
}
From your FirstActivity.java:
TabLayout mTabLayout;
ViewPager mViewPager;
TabsPagerAdapte mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
// Tab layout
mTabLayout = (TabLayout) findViewById(R.id.tabs);
// View pager
mViewPager = (ViewPager) findViewById(R.id.view_pager);
// Adapter
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// 2 Tabs
mAdapter.addFrag(new FragmentOne(), "ONE");
mAdapter.addFrag(new FragmentTwo(), "TWO");
mViewPager.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
From your SecondActivity.java:
TabLayout mTabLayout;
ViewPager mViewPager;
TabsPagerAdapte mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// Tab layout
mTabLayout = (TabLayout) findViewById(R.id.tabs);
// View pager
mViewPager = (ViewPager) findViewById(R.id.view_pager);
// Adapter
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// 2 Tabs
mAdapter.addFrag(new FragmentOne(), "ONE");
mAdapter.addFrag(new FragmentTwo(), "TWO");
mViewPager.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
From your ThirdActivity.java:
TabLayout mTabLayout;
ViewPager mViewPager;
TabsPagerAdapte mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
// Tab layout
mTabLayout = (TabLayout) findViewById(R.id.tabs);
// View pager
mViewPager = (ViewPager) findViewById(R.id.view_pager);
// Adapter
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// 3 Tabs
mAdapter.addFrag(new FragmentOne(), "ONE");
mAdapter.addFrag(new FragmentTwo(), "TWO");
mAdapter.addFrag(new FragmentThree(), "THREE");
mViewPager.setAdapter(mAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
Hope this will help~
You can use the same class. Just make sure your overridden methods can differentiate which activity it is in. So getCount() in FragmentPagerAdapter as an example would return two in your 1st and 2nd activity, but three in your 3rd one. Same goes for layouts.
yes, you can use this pageradapter class for each activity. it will create size that you want in a activity
public class ExamplePagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ExamplePagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}

Android - How to call method in fragment from activity [duplicate]

This question already has answers here:
Calling a Fragment method from a parent Activity
(14 answers)
Closed 5 years ago.
How can i call method in fragment from activity?
I searched some code but most of people said use like this,
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.specific_function_name();
but i don't have fragment in my xml
I need another way to call fragment method.
This is method in fragment
public void video()
{
new getVideo().execute();
}
And this is my activity
public class ActivityTwitch extends AppCompatActivity
{
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitch);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("개구멍");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new TwitchChannel(), "채널");
adapter.addFragment(new TwitchStream(), "스트리밍");
adapter.addFragment(new TwitchFeed(), "게시물");
adapter.addFragment(new TwitchVideo(), "동영상");
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
public class Adapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm)
{
super(fm);
}
public void addFragment(Fragment fragment, String title)
{
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position)
{
return mFragments.get(position);
}
#Override
public int getCount()
{
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitles.get(position);
}
}
#Override
public void onBackPressed()
{
super.onBackPressed();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}
If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag() instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");

How to set icon for whole tab button?

How to set icon for whole tab button?
This code is download from the internet and The text the tab doesnt have to be there.
....
I apologize for the perfect English translation. The picture speaks for itself
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.likepress,
R.drawable.kufrpress,
R.drawable.referralpress,
R.drawable.changepress
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
adapter.addFrag(new ThreeFragment(), "For");
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 null;
}
}
}
You can use tabLayout.getTabAt(i)setCustomView(view) to place a custom view for each tab. For example it can be an ImageView with your icon

Categories

Resources