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");
Related
I'm using Fragments to change scenes in my application, and I've come across the problem where when the phone back button is pressed, the application closes. How would I make it so when the back button is pressed, the previous fragment opens.
I searched for solutions and there are quite a few like using getChildFragmentManager or back stack. I just don't know how to implement it for my specific state pager adapter, of which I followed a youtube video tutorial for.
SectionsStatePagerAdapter.java:
public class SectionsStatePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
public SectionsStatePagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public SectionsStatePagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
public void addFragment(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
public SectionsStatePagerAdapter mSectionsStatePagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Fragment Stuff:
mSectionsStatePagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
//SetUpPager:
setupViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager){
SectionsStatePagerAdapter adapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new MainPageFragment(),"MainPage"); //0
adapter.addFragment(new CoffeePageFragment(),"CoffeePage"); //1
adapter.addFragment(new RegularCoffeeFragment(),"RegularCoffeePage"); //2
viewPager.setAdapter(adapter);
}
public void setViewPager(int fragmentNumber){
mViewPager.setCurrentItem(fragmentNumber);
}
}
CoffeePageFragment.java:
public class CoffeePageFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_coffee_page,container,false);
btnRegularCoffee = view.findViewById(R.id.regular_coffee_button);
btnRegularCoffee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setViewPager(2);
}
});
return (view);
}
}
In conclusion, how do I make it so when the device back button is pressed, it will go back to the previous fragment?
In previous versions of the AppCompatActivity implementation it was enough to override onBackPressed() in your activity, newer versions dictate to implement the OnBackPressedCallback, like shown here: https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher.html
public class FormEntryFragment extends Fragment {
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(
true // default to enabled
) {
#Override
public void handleOnBackPressed() {
showAreYouSureDialog();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(
this, // LifecycleOwner
callback);
}
}
It might still be ok to use onBackPressed on the Activity level, though.
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");
}
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);
}
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);
}
}
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