How To Set Default Layout in Android - java

I have a two layouts that scroll back and forth in an Activity. When I press the home button, it returns to the first layout. What I want to do is set the "home" layout to be the second layout i.e. when i press the home button I want it to return to the second screen and not the first. I am having trouble doing this, if anyone could help me I would be very grateful. I didn't include the XML files they have nothing important.
Launcher.java
public class Launcher extends FragmentActivity {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher)
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
}
}
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_apps,container,false);
}
}
Fragment2.java
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_homescreen,container,false);
}
}

If you are using PagerAdapter then use this line to set your default layoutmViewPager.setCurrentItem(1); this will set your 2nd layout as default, layout number starts from 0,1,2,...
Hope this thing help you out.

In this link Set default page for ViewPager in Android, i feel it is the same problem. Maybe it can help you.

Related

ViewPager2 doesn't show Fragments

I am trying to implement ViewPager2 in my application and this is not the first time I am doing it but now it is not working.
I've been trying to find a solution for a couple of hours and trying different options but still - the fragments don't show up.
ViewPager2 is displaying correctly - I checked this by changing its background color.
I'm using the OneUI 2.4.0 library - but I've tested this library before and everything worked, and now it won't.
ViewPager2 Adapter
public class MainViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public MainViewPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new MainFragment();
case 1:
return new NewsFragment();
case 2:
return new ProfileFragment();
}
return null;
}
#Override
public int getItemCount() {
return 3;
}
}
MainFragment.java (other fragments code looks the same)
public class MainFragment extends Fragment {
View mRootView;
#Nullable
#Override
public View onCreateView(
#NonNull LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_main, container, true);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("MainFragment", "Initialized"); // I don't see that in logcat
}
}
fragment_main.xml (Other fragments have similar layout)
<?xml version="1.0" encoding="utf-8"?>
<de.dlyt.yanndroid.oneui.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.textview.MaterialTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/main_page"
android:textColor="#color/sesl_primary_text"
android:textSize="24sp"
android:textStyle="bold" />
</de.dlyt.yanndroid.oneui.widget.NestedScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ToolbarLayout mToolbarLayout;
private ViewPager2 mViewPager;
private TabLayout mTabLayout;
private MainViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
setup();
}
private void initialize() {
mToolbarLayout = (ToolbarLayout) findViewById(R.id.mToolbarLayout);
mViewPager = (ViewPager2) findViewById(R.id.mMainPager);
mTabLayout = (TabLayout) findViewById(R.id.mMainTabLayout);
}
private void setup() {
viewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), getLifecycle());
mViewPager.setAdapter(viewPagerAdapter);
}
And the problem is just that i don't see my fragments in ViewPager2.
try to
return mRootView
instead of
return super.onCreateView(inflater, container, savedInstanceState);
The place where you went wrong was when you did not add the layout to the root. The problem is this:
return super.onCreateView(inflater, container, savedInstanceState);
but, you r not using your view right? You are using the default view which is just empty. So, to solve it, you need to pass it your view instead of that. So, return your view like this:
return mRootView;

Accessing a fragment from MainActivity return null (can not call fragment methods)

I have googled everything during a day about the subject and nothing seems to work around for my project. I have added a viewpager to my main activity. There is two fragments attached to it thanks to a page adapter. I initialized everything on the OnCreate method from my main activity. The view pager work well. The problem is when I want to access from my MainActivity the textviews included in my fragments. I created a Set method in each fragment which modify the textviews accordingly to the arguments. So in order to call this method from my MainActivity I have to instantiate the fragments on my MainActivity and the problem is that this line of code return null and the fragments can not be instantiated. Here is the code used for testing this purpose.
Main Activity
public class MainActivity extends AppCompatActivity{
private SecondActivitySwipeAdapter adapterViewPager;
private FirstFragmentSwipe fragment1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
setContentView(R.layout.main_activity_test);
ViewPager vpPager = (ViewPager) findViewById(R.id.viewpager);
adapterViewPager = new SecondActivitySwipeAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
fragment1 = (FirstFragmentSwipe) adapterViewPager.getRegisteredFragment(vpPager.getCurrentItem());
fragment1.setTextViews(1,2,3,4,5);
}
...
}
SecondActivitySwipeAdapter
public class SecondActivitySwipeAdapter extends FragmentStatePagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
private static int NUM_ITEMS = 2;
private FragmentManager mFragmentManager;
public SecondActivitySwipeAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
mFragmentManager = fragmentManager;
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstFragmentSwipe.newInstance();
case 1:
return SecondFragmentSwipe.newInstance();
default:
return null;
}
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
FirstFragmentSwipe
public class FirstFragmentSwipe extends Fragment {
private TextView avg1;
private TextView avg2;
private TextView avg3;
private TextView avg4;
private TextView avg5;
public static FirstFragmentSwipe newInstance(){
return new FirstFragmentSwipe();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.swipelayout1, container, false);
avg1 = view.findViewById(R.id.pwrAvgNmbview1);
avg2 = view.findViewById(R.id.pwrAvgNmbview2);
avg3 = view.findViewById(R.id.pwrAvgNmbview3);
avg4 = view.findViewById(R.id.pwrAvgNmbview4);
avg5 = view.findViewById(R.id.pwrAvgNmbview5);
return view;
}
public void setTextViews(int avg1, int avg2, int avg3, int avg4, int avg5){
this.avg1.setText(Integer.toString(avg1));
this.avg2.setText(Integer.toString(avg2));
this.avg3.setText(Integer.toString(avg3));
this.avg4.setText(Integer.toString(avg4));
this.avg5.setText(Integer.toString(avg5));
}
}
The second fragment is basically the same as fragment for the moment. I am using some ideas found by googling. The last line of the onCreate method make the app crash. Thanks for you precious help.
So the problem here is that registeredFragments doesn't have the fragments instantiated yet.
First you can check if fragment1 is null to prevent crashes.
Furthermore you'd rather put initialization methods in getItem() of adapter or in onViewCreated() of the fragment and do some updates in later lifecycle methods if needed.

Recover EditText's value from a fragment to another

My EditText is in my fragment named : EquationsCalculFragment.java
I want to recover the value in my fragment named : EquationsResultat.java
I have two NullPointerException with no apparent reasons (see the comments directly in the code).
NB : For the error in the EquationsResultsFragment, I tried to cast with String.valueOf(), with Float.parseFloat(), with the two combined... but no one worked.
EquationsCalculFragment.java
public class EquationsCalculFragment extends Fragment {
private ViewPager viewPager;
private EditText champ_a;
private EditText champ_b;
private String a;
private String b;
public float getA_equa_2nd() {
return Float.parseFloat(a);
}
public float getB_equa_2nd() {
return Float.parseFloat(b);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_equations_calcul, container, false);
viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
champ_a = (EditText) view.findViewById(R.id.equa_2nd_a);
champ_b = (EditText) view.findViewById(R.id.equa_2nd_b);
Button button = (Button) view.findViewById(R.id.btn_equations_resultats);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b = champ_b.getText().toString();
a = champ_a.getText().toString();
EquationsResultatFragment eqResFr = new EquationsResultatFragment();
eqResFr.getResultat(getA_equa_2nd(), getB_equa_2nd()); //NullPointerException happens here
//at com.example.slabre.applitest.EquationsCalculFragment$1.onClick(EquationsCalculFragment.java:60)
viewPager.setCurrentItem(1, true);
}
});
return view;
}
}
EquationsResultat.java
public class EquationsResultatFragment extends Fragment {
private TextView results;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_equations_resultat, container, false);
results = (TextView) view.findViewById(R.id.equa_2nd_resultat);
return view;
}
public void getResultat(float a, float b) {
results.setText(String.valueOf((a*a)+(2*a*b)+(b*b))); // NullPointerException happens here
// at com.example.slabre.applitest.EquationsResultatFragment.getResultat(EquationsResultatFragment.java:29)
}
}
Hope you can help me, I think this is not a big problem.
Parent Activity : TabFragment.java (yes my app si working with a TabLayout and ViewPager)
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new EquationsCalculFragment();
case 1 : return new EquationsResultatFragment();
case 2 : return new EquationsInfosFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Calcul";
case 1 :
return "Résultats";
case 2 :
return "Infos";
}
return null;
}
}
}
First of all, you cannot directly communicate between different fragments. You need to go through your container activity for it.
Declare a listener interface through which your fragment will communicate with your container activity. Attach that listener to your EquationsCalculFragment. Your container activity should implement that listener.
Now when you EquationsCalculFragment wants to communicate with EquationsResultatFragment you notify your container activity using that listener. In the container activity, when you get the listener callback, grab your EquationsResultatFragment fragment instance using findFragmentById(int id) or findFragmentByTag(String tag) and check if it is already added to your container activity. If it is, then call any public method of EquationsResultatFragment fragment, using that grabbed EquationsResultatFragment fragment instance.
Check out this link for more details and sample code.
EquationsResultat's getResultat is called when you click on the EquationsCalculFragment's button, and should set EquationsResultat's TextView (results) text. Problem is, results is set on EquationsResultat's onCreateView, and it seems this method has no been called yet, and therefore results is still null.
Post your activitie's code, it will be easier to help you knowing when you are attaching the fragments, etc.
Try this!!
public void getResultat(float a, float b) {
results.setText(((a * a) + (2 * a * b) + (b * b))+"");
}

Handling Screen Rotation for Fragment inside of View(State)PagerAdapter inside Fragment

Hello kind (android) programmers,
The situation is as follows:
I have an activity that uses a NavigationDrawer that allows to load 3 fragments. Inside one of those fragments I have a ViewStatePagerAdapter, which on it's turn hosts 3 fragments. In one of those fragments I load a bunch of databasedata using a cursorloader. These values are editable to a new value, but should not be persisted to DB until a certain button is clicked.
All this works fine, but the problem is that when I now rotate the screen, all the changed data is gone. I tried using onSaveInstance in the inner fragment itself, but I think the problem lies higher, as I already noticed than when I rotate the screen, the viewpager jumps back to the first tab.
What would be the correct way (/correct location: activity, certain fragment,...) to:
Make sure the viewpager remains on the right tab
Remembers the data that changed in the inner fragment
The fragment that contains the viewpager currently has following onCreateView :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, null);
tabLayout = (TabLayout) v.findViewById(R.id.fragment_tabs);
viewPager = (ViewPager) v.findViewById(R.id.fragment_viewpager);
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
return v;
}
and an inner class for the FragmentStatePagerAdapter
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return PersonFragment.newInstance();
case 1 : return FriendsFragment.newInstance();
case 2 : return EventsFragment.newInstance();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "ME";
case 1 :
return "FOLLOWING";
case 2 :
return "EVENTS";
}
return null;
}
}
nothing special happening for the rest in here. (Which maybe should?)
The fragment inside of the viewpager has following onCreate/onCreateView
#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_person, container, false);
this.viewHolder = new ViewHolder(rootView);
if (savedInstanceState != null) {
CharSequence savedPersonName = savedInstanceState.getCharSequence("personName");
if (savedPersonName != null) {
Log.v("PersonFragment", savedPersonName.toString());
this.viewHolder.personnameView.setText(savedPersonName);
}
}
return rootView;
}
Thanks in advance.
You probably know this already but this is the kind of thing I would do to address your second issue
private TextView tvTitle;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.mylayout, container, false);
tvTitle = (TextView) rootView.findViewById(R.id.mytitle);
if (savedInstanceState != null) {
CharSequence csTitle = savedInstanceState.getCharSequence("myTitle");
if (csTitle != null) tvTitle.setText(csTitle);
}
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putCharSequence("myTitle", tvTitle.getText());
}

How to get the position of the fragment in an Activity?

I am new to android. I have a sliding tab layout and a viewpager with a fragment. I have setup a basic link between these to switch tabs for a count of 5(i.e 5 tabs) The problem is that, in each of these tabs, I want to populate a listview using simplecursoradapter, for which I need the position of each fragment so that I could populate it accordingly. I have got the position in the fragment adapter class, but I am unable to pass it to the main activity. Also, How can I access DBadapter inside my fragment class to populate listview from the database? or is there some other way to do this? Below is my code. Any help is greatly appreciated. Thanks in advance.
public class myFragment extends Fragment{
private ListView mainList;
public static myFragment getInstance(int position){
myFragment MyFragment = new myFragment();
Bundle args = new Bundle();
args.putInt("position", position);
MyFragment.setArguments(args);
return MyFragment;
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_main_list,container, false);
mainList = (ListView)layout.findViewById(R.id.mainListView);
Bundle bundle = getArguments();
if(bundle!=null){
if(bundle.getInt("position")==0){
mainList.setBackgroundColor(getResources().getColor(R.color.primary500));
}
else if(bundle.getInt("position")==1){
mainList.setBackgroundColor(getResources().getColor(R.color.primary100));
}
else if(bundle.getInt("position")==2){
mainList.setBackgroundColor(getResources().getColor(R.color.primary700));
}
else if(bundle.getInt("position")==3){
mainList.setBackgroundColor(getResources().getColor(R.color.accent));
}
else if(bundle.getInt("position")==4){
mainList.setBackgroundColor(getResources().getColor(R.color.black));
}
}
return layout;
}
}
The Main Activity is as follows:
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
private ViewPager mPage;
private SlidingTabLayout mTabs;
DBadapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openDB();
toolbar = (Toolbar)findViewById(R.id.app_bar);
mPage = (ViewPager)findViewById(R.id.pager);
mTabs = (SlidingTabLayout)findViewById(R.id.tabs);
mFab = (FloatingActionButton)findViewById(R.id.fab);
setSupportActionBar(toolbar);
mPage.setAdapter(new myPagerAdapter(getSupportFragmentManager()));
mTabs.setViewPager(mPage);
}
public class myPagerAdapter extends FragmentPagerAdapter{
String[] tabs;
public myPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
myFragment MyFragment = myFragment.getInstance(position);
return MyFragment;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 5;
}
}
Use this method :
mPage.setOnPageChangeListener(new SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
// pos is the position of fragment that app showing
});
UPDATE
in your view pager adapter :
public Fragment getItem(int position) {
return new myFragment(position);
}
And in your fragment class :
public class myFragment extends Fragment{
private int pos
public void myFragment(int position){
this.pos = position;
}
// other code of your class

Categories

Resources