ViewPager Fragment occasionally wont inflate/load - android

I've searched in many places and tried many solutions to the following problem, I hope you can help!
I've made a Tabbed Activity with 6 fragments, and a logging screen from a blank activity. The Tabbed activity is the main activity which has a ViewPager container to show the actual tab, however the logging activity is the first one to load and show. Somewhere along the process (very far into it actually) I've noticed that the fragments inside the container will occasionally wont show. They would sometimes reappear when I rotate the screen, or when I use the Logout feature from the menu and then login back in (sometimes takes several tries until is shows back up).
I've read through but could't figure it out.
I've tried changing the
(getChildFragmentManager(), getResources()));
but I think I don't place it in the right spot.
My MainActivty
public class MainActivity extends AppCompatActivity {
private boolean verified;
public static String token;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the Intent that started this activity and extract the string
Bundle extras = getIntent().getExtras();
if (extras != null) {
verified = extras.getBoolean("verify");
token = extras.getString("token");
Toast.makeText(getBaseContext(), "Login Successful",
Toast.LENGTH_SHORT).show();
}
if(verified != true) {
logoutSuccessful();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the
three
// primary sections of the activity.
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager());
//mSectionsPagerAdapter.saveState();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//getSupportActionBar().setIcon(R.drawable.logo_small);
//set icons for tabs
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if (i == 0) {
tabLayout.getTabAt(i).setIcon(R.drawable.icon_scan);
} else {
if (i == 1) {
tabLayout.getTabAt(i).setIcon(R.drawable.icon_pricecheck);
} else {
tabLayout.getTabAt(i).setIcon(R.drawable.logo_small);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_logout) {
logoutSuccessful();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
//DELETED PLACEHOLDER CLASS
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
below).
// return PlaceholderFragment.newInstance(position + 1);
switch (position){
case 0: Tab1 tab1 = new Tab1();
return tab1;
case 1: Tab2 tab2 = new Tab2();
return tab2;
case 2: Tab3 tab3 = new Tab3();
return tab3;
case 3: Tab4 tab4 = new Tab4();
return tab4;
case 4: Tab5 tab5 = new Tab5();
return tab5;
case 5: Tab6 tab6 = new Tab6();
return tab6;
}
return null;
}
#Override
public int getCount() {
// Show total pages.
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SCAN";
case 1:
return "PRICE CHECK";
case 2:
return "SECTION 3";
case 3:
return "SECTION 4";
case 4:
return "SECTION 5";
case 5:
return "SECTION 6";
}
return null;
}
}
private void logoutSuccessful(){
Intent myIntent = new Intent(MainActivity.this, Login.class);
MainActivity.this.startActivity(myIntent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
finish();
}
}
Tab1:
public class Tab1 extends android.support.v4.app.Fragment {
Button btnUpc;
EditText txtUPC;
Vector<UPCProductObject> v = new Vector<>();
Editable value;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab1, container,false);
lblUpcResult = (TextView) v.findViewById(R.id.lblUPCResult);
txtUPC = (EditText) v.findViewById(R.id.txtUPC);
btnUpc = (Button) v.findViewById(R.id.btnUPC);
btnUpc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
//hide keyboard
InputMethodManager mgr = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(txtUPC.getWindowToken(), 0);
btnUpc.setEnabled(false);
value = txtUPC.getText();
new searchUPC().execute();
}});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
getChildFragmentManager().beginTransaction()
.add(R.id.container, new Tab1(), "Scan")
.commit();
}
}
activity_main xml:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.dabush.shen.mcrpos.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="90dp"
android:layout_height="50dp"
android:src="#drawable/logo_small"
android:layout_gravity="left"
/>
</FrameLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="75dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:minHeight="80dp">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/textColorPrimary"
app:tabTextColor="#FFD5D2D2" />
</android.support.design.widget.AppBarLayout>
<!--FLOATING EDITABLE BUTTON
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
-->
tab1 xml
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="13dp"
android:layout_toLeftOf="#+id/tblSearch"
android:layout_toStartOf="#+id/tblSearch" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab1_title"
android:textSize="24sp"
android:layout_alignTop="#+id/section_label"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="#string/scan_desc"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:id="#+id/tblSearch"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/txtUPC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:textAlignment="center" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="0dp">
<Button
android:id="#+id/btnUPC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SEARCH" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" />
</TableLayout>
<TextView
android:id="#+id/lblUPCResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tblSearch"
android:layout_centerHorizontal="true"
android:layout_marginTop="91dp"
android:textAlignment="center"
android:textSize="12sp" />
<ListView
android:id="#+id/listUpc"
android:layout_width="match_parent"
android:layout_height="375dp"
android:layout_below="#+id/tblSearch"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:textAlignment="center" />

You dont need to getChildFragmentManager().beginTransaction() in ur 1st fragment. And in activity lifecycle, onRotate, activity was destroyed and recreate, you need to save it on saveInstance and reload UI onRestoreInstance

Related

Changing fragments onClick of a button

I am trying to change the fragment when I click on a button. The button is inside a fragment and I want to go to another fragment. This code is not giving any error but not changing to desired fragment. It is just showing the background of container. Please help me why it is just showing the color of container and not changing to new fragment.
Here is my first Fragment-
public class IntroFragment1 extends Fragment {
public IntroFragment1() {
// Required empty public constructor
}
public static IntroFragment1 newInstance() {
return new IntroFragment1();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_intro1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/**
* Button to go to next tab in tutorial
* */
Button nextScreen = getView().findViewById(R.id.nextTabButtonIntro);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (vb1 != null) {
vb1.vibrate(300);
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment frag = IntroFragment2.newInstance();
transaction.replace(R.id.containerIntroScreen, frag);
transaction.commit();
}
});
}//End of onViewCreated
}
This is the XML of first Fragment. The next Button should take me to next fragment-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
android:orientation="vertical"
android:weightSum="1"
tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroFragment1">
<TextView
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="casual"
android:text="Track your daily activities. Stay healthy, Stay smart."
android:textSize="26dp" />
<Button
android:id="#+id/skipIntoButton"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_weight="1"
android:background="#drawable/background_button"
android:fontFamily="casual"
android:text="skip"
android:textAllCaps="true"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
android:textColor="#000" />
<Button
android:id="#+id/nextTabButtonIntro"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_weight="1"
android:background="#drawable/background_button"
android:fontFamily="casual"
android:text="next"
android:textAllCaps="true"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Large"
android:textColor="#000" />
</LinearLayout>
This is the fragment, I want to go to-
public class IntroFragment2 extends Fragment {
public IntroFragment2() {
// Required empty public constructor
}
public static android.support.v4.app.Fragment newInstance() {
IntroFragment2 fragment = new IntroFragment2();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_intro2, container, false);
}
The XML of the 2nd Fragment-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroFragment2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:text="2nd fragment" />
</RelativeLayout>
This is the layout of activity which has the fragments-
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroScreen">
<android.support.v4.view.ViewPager
android:background="#00F111"
android:id="#+id/containerIntroScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
So initially the app opens with 1st transaction as expected. However when I click on next button in fragment 1, it should take me to fragment 2. But it just shows the Background color of ViewPager after the Fragment Transaction.
EDIT:
Here is my Main Activity as well which has the fragments-
public class IntroScreen extends AppCompatActivity {
public static Vibrator vb1;
public Button nextScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro_screen);
/***/
vb1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
/**
* Create the adapter that will return a fragment
* for each of the N primary sections of the activity.
* */
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
/** Set up the ViewPager with the sections adapter.*/
ViewPager mViewPager = findViewById(R.id.containerIntroScreen);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (position) {
case 0:
return IntroFragment1.newInstance();
case 1:
return IntroFragment2.newInstance();
default:
return IntroFragment2.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
}
SOLVED BY #MikeM. in the comments above.
Since I was already using a ViewPager, All that was required was to give the correct item number to my ViewPager.
int THE_POSITION_OF_THE_FRAGMENT_IN_VIEW_PAGER = 1;
mViewPager.setCurrentItem(THE_POSITION_OF_THE_FRAGMENT_IN_VIEW_PAGER);

Setonitemclicklistener inside fragment of tabbed activity

I'm new in android and I want to make a project, but I have a problem with inserting a list view inside fragment of tabbed activity which can pass to another activity when clicked. Before I asked here, I already tried to search the solution but it didn't work, I hope anyone in here can solve my problem.
Here's my code
Service Activity as a Tab host
public class ServiceActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//deleted PlaceHolderFragment
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
Sinspection sins = new Sinspection();
return sins;
case 1:
Minspection mins = new Minspection();
return mins;
case 2:
Linspection lins = new Linspection();
return lins;
case 3:
WRinspection wrins = new WRinspection();
return wrins;
default:
return null;
}
}
#Override
public int getCount() {
// Show total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "S Inspection";
case 1:
return "M Inspection";
case 2:
return "L Inspection";
case 3:
return "When Required";
}
return null;
}
}
Fragment Class
public class Linspection extends ListFragment {
String [] linsp = {
"Differential Oil and Filter",
"Hub and Reduction Gear Oil",
"Wheel Nut",
"Air Dryer Filter"
};
ArrayAdapter<String> adapter;
ListView listView;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
listView = (ListView)getActivity().findViewById(R.id.listViewL);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.
simple_list_item_1,linsp);
setListAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position){
case 0:
Intent intent = new Intent(getActivity(), EngineOil.class);
startActivity(intent);
}
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
I want to pass to this activity
public class EngineOil extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.s_engine_oil);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
}
}
This is my xml:
activity_service
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listViewL"
>
</ListView>
</RelativeLayout>
activity destionation xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="?attr/actionBarTheme"
android:minHeight="?attr/actionBarSize"
android:id="#+id/toolbar3"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/viewPager"
android:layout_marginTop="20dp"
android:layout_below="#+id/toolbar3"
android:layout_alignParentStart="true">
</android.support.v4.view.ViewPager>
</RelativeLayout>
When I run the application it "always keep crashing". I don't know how to fix it, and hope you can help me to solve my problem
Thanks in advance
I made a project for you to use as reference.
`activity_main`
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabHost
android:id="#+id/tabHost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/ll_cashier_invoice"
android:baselineAligned="false"
android:gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="4dip">
<fragment
android:id="#+id/frag_invoice"
android:name="com.example.sydney.sample.MainActivity$FirstFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/tab4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
`fragment1.xml`
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/myArray" />
</LinearLayout>
`MainActivity.java`
public class MainActivity extends Activity {
ListView lv;
TabHost host;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
host = (TabHost)findViewById(R.id.tabHost);
host.setup();
lv = (ListView)findViewById(R.id.list);
TabHost.TabSpec spec = host.newTabSpec("Sinspection");
spec.setContent(R.id.tab1);
spec.setIndicator("Sinspection");
host.addTab(spec);
//Tab 2
spec = host.newTabSpec("Minspection");
spec.setContent(R.id.tab2);
spec.setIndicator("Minspection");
host.addTab(spec);
//Tab 3
spec = host.newTabSpec("Linspection");
spec.setContent(R.id.tab3);
spec.setIndicator("Linspection");
host.addTab(spec);
//Tab 4
spec = host.newTabSpec("Winspection");
spec.setContent(R.id.tab4);
spec.setIndicator("Winspection");
host.addTab(spec);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(MainActivity.this,NextActivity.class);
startActivity(myIntent);
}
});
}
public static class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
}
}
Click here for the full code.

Replace Fragment in ViewPager

I am following example from Android doc example here: https://developer.android.com/training/animation/screen-slide.html
I was wondering if I want several different fragments on each page then what would be the best approach.
This is my MainActivity, as you can see I open new fragment class for each page position:
public class MainActivity extends AppCompatActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 4;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new MainActivity.ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 4 HeartsPageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HeartsPageFragment();
case 1:
return new DiamondsPageFragment();
case 2:
return new ClubsPageFragment();
case 3:
return new SpadesPageFragment();
}
return null;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
This is one of the fragment classes, all four are almost same:
public class ClubsPageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.view_clubs, container, false);
return rootView;
}
}
I was wondering if it's best approach to have four different fragment classes for each page? I feel like this is repetition and bad, but I am not sure how I could fix this. It is lagging on my phone to when I switch between those. Any tips would be welcome.
Edit:
Here is the code for the layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/content_suit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/first_row_hearts">
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView1"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_2"/>
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView2"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_3"/>
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView3"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_4"/>
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView4"
android:src="#drawable/spades_5"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/second_row_hearts"
android:layout_below="#id/first_row_hearts"
android:layout_marginTop="10dp">
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView5"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_6" />
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView6"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_7" />
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView7"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_8" />
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView8"
android:src="#drawable/spades_9" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/third_row_hearts"
android:layout_below="#id/second_row_hearts"
android:layout_marginTop="10dp">
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView9"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_10" />
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView10"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_jack" />
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView11"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_queen" />
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView12"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_king"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fourth_row_hearts"
android:layout_below="#+id/third_row_hearts"
android:layout_marginTop="10dp">
<ImageView
android:layout_width="80dp"
android:layout_height="112dp"
android:id="#+id/imageView13"
android:layout_marginEnd="10dp"
android:src="#drawable/spades_ace"/>
</LinearLayout>
</RelativeLayout>
If you donot want to make different fragment classes study this auto generated code of tabbed activity android.
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
LeftDrawerLayout mLeftDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 7 total pages.
return 7;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
case 3:
return "SECTION 4";
case 4:
return "SECTION 5";
case 5:
return "SECTION 6";
case 6:
return "SECTION 7";
}
return null;
}
}
}

My code seems to go twice in my switch case

I'm applying an example seen on the net to my code, to implement an introduction page (ViewPager with 4 pages).
For that I use the native code provided by Android Studio when creating a new activity.
I adapted the following code that write texte depending on the fragment we're on :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
To the following code, with a switch, to display different thing (button color, texte, icon) depending on the fragment we're on:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
View rootView = inflater.inflate(R.layout.fragment_welcome, container, false);
TextView textViewTitle = (TextView) rootView.findViewById(R.id.txtViewWelcomeTitle);
TextView textViewDesc = (TextView) rootView.findViewById(R.id.txtViewWelcomeDesc);
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageViewWelcome);
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
imageView.setImageResource(R.drawable.ic_menu_camera);
textViewTitle.setText(R.string.fragment_1_title);
textViewDesc.setText(R.string.fragment_1_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen1));
btnNext.setText(R.string.next);
btnSkip.setVisibility(View.VISIBLE);
/*btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// launch next page of the fragment.
}
});*/
break;
case 2:
imageView.setImageResource(R.drawable.ic_menu_gallery);
textViewTitle.setText(R.string.fragment_2_title);
textViewDesc.setText(R.string.fragment_2_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen2));
btnNext.setText(R.string.next);
btnSkip.setVisibility(View.VISIBLE);
break;
case 3:
imageView.setImageResource(R.drawable.ic_menu_manage);
textViewTitle.setText(R.string.fragment_3_title);
textViewDesc.setText(R.string.fragment_3_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen3));
btnNext.setText(R.string.next);
btnSkip.setVisibility(View.VISIBLE);
break;
case 4:
imageView.setImageResource(R.drawable.ic_menu_send);
textViewTitle.setText(R.string.fragment_4_title);
textViewDesc.setText(R.string.fragment_4_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen4));
btnNext.setText(R.string.start);
btnSkip.setVisibility(View.INVISIBLE);
break;
}
return rootView;
}
What I was hopping to see is 4 pages, with two button (Skip and Next) on 3 of them, and the Start button on the 4th.
What I see : The 2 button only on the 2 first pages, and the "start" button on the pages 3 and 4.
When I debug my app, it seems that my code go through the case 1, then through the case 2, and after that my app is displaying the case 1 page.
This means that, when I switch, my pages seems to be +1 of the position they should be (my page 1 is finally the 2, the 2 is the 3, ...).
The strange thing is that my texte and icons displayed are the right ones.
Hereunder is the complete WelcomActivity :
public class WelcomeActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
public static final String PREFS_NAME = "StartPref";
private PrefManager prefManager;
private static LinearLayout dotsLayout;
private static TextView[] dots;
private static Button btnSkip, btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
/* prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
goToHomePage();
finish();
}
*/
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_welcome);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// making notification bar transparent
changeStatusBarColor();
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToHomePage(v);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_welcome, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
View rootView = inflater.inflate(R.layout.fragment_welcome, container, false);
TextView textViewTitle = (TextView) rootView.findViewById(R.id.txtViewWelcomeTitle);
TextView textViewDesc = (TextView) rootView.findViewById(R.id.txtViewWelcomeDesc);
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageViewWelcome);
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
imageView.setImageResource(R.drawable.ic_menu_camera);
textViewTitle.setText(R.string.fragment_1_title);
textViewDesc.setText(R.string.fragment_1_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen1));
btnNext.setText(R.string.next);
btnSkip.setVisibility(View.VISIBLE);
/*btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// launch next page of the fragment.
}
});*/
break;
case 2:
imageView.setImageResource(R.drawable.ic_menu_gallery);
textViewTitle.setText(R.string.fragment_2_title);
textViewDesc.setText(R.string.fragment_2_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen2));
btnNext.setText(R.string.next);
btnSkip.setVisibility(View.VISIBLE);
break;
case 3:
imageView.setImageResource(R.drawable.ic_menu_manage);
textViewTitle.setText(R.string.fragment_3_title);
textViewDesc.setText(R.string.fragment_3_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen3));
btnNext.setText(R.string.next);
btnSkip.setVisibility(View.VISIBLE);
break;
case 4:
imageView.setImageResource(R.drawable.ic_menu_send);
textViewTitle.setText(R.string.fragment_4_title);
textViewDesc.setText(R.string.fragment_4_desc);
rootView.setBackgroundColor(ContextCompat.getColor(context, R.color.bg_screen4));
btnNext.setText(R.string.start);
btnSkip.setVisibility(View.INVISIBLE);
break;
}
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
case 3:
return "SECTION 4";
}
return null;
}
}
public void goToHomePage(View view) {
prefManager.setFirstTimeLaunch(false);
Intent intent = new Intent(this, HomePageActivity.class);
startActivity(intent);
}
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
private void addBottomDots(int currentPage) {
dots = new TextView[mSectionsPagerAdapter.getCount()];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
}
And here are the fragment_welcome.xml, then the activity_welcome.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_screen1"
tools:context="com.example.avescera.remindme.WelcomeActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="#dimen/img_width_height"
android:layout_height="#dimen/img_width_height"
android:src="#drawable/ic_menu_manage"
android:id="#+id/imageViewWelcome" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_title"
android:textStyle="bold"
android:id="#+id/txtViewWelcomeTitle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingLeft="#dimen/desc_padding"
android:paddingRight="#dimen/desc_padding"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="#dimen/slide_desc"
android:id="#+id/txtViewWelcomeDesc" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.avescera.remindme.WelcomeActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="#dimen/dots_height"
android:layout_marginBottom="#dimen/dots_margin_bottom"
android:gravity="center"
android:orientation="horizontal"
android:layout_alignParentBottom="false"
android:layout_below="#+id/viewDots"
android:layout_gravity="bottom|center_horizontal"></LinearLayout>
<View
android:id="#+id/viewDots"
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:background="#android:color/white"
android:layout_gravity="bottom|center" />
<Button
android:id="#+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#null"
android:text="#string/next"
android:textColor="#android:color/white"
android:layout_gravity="bottom|left" />
<Button
android:id="#+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#null"
android:text="#string/skip"
android:textColor="#android:color/white"
android:layout_gravity="bottom|right" />
</android.support.design.widget.CoordinatorLayout>
If you need any furhter information, do not hesitate.
Alex
finally I find out how to answer to my issue (for those who would be interested in resolving this issue).
First of all, some more details. I used the built in activity tabbed-activity provided by android studio (2.2). This one allow to have fragment pager use, and it seems that the behavior (showing for example the first fragment, but in your code, you're already in the second one, did not correctly understood how this is working).
For me, I wanted to have 4 pages (my fragment pager with 4 parts) and 2 buttons at the bottom (attached to the activity xml and not to the fragment xml).
The solution is simlpe : add the fragment text update in the onCreateView() part and the button text update (and the onClickListener) in the OnCreate() part.
In the OnCreate() part, to know which page fragment is used, you'll have to use the ViewPager, with the addOnPageChangeListener on it. Then it's ok, you can add a switch in it to know which page, checking the value of the position (from 0 to the number of page - 1 you have).
Hope this helps.

how to show a textview on top of viewpager actionbar and under the supportactionbar

I am trying to show a TextView between the main actionbar and viewpager action bar but it is showing under the viewpager action bar. here is my code
promotions.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/promotionheader"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:gravity="center"
android:layout_alignParentTop="true"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/txtViewHeading"
android:text="#string/heading_promotion"
android:textColor="#color/white"
android:textSize="18sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/border_promotion"
android:padding="10dp"
android:gravity="center_vertical|center_horizontal" />
</LinearLayout>
<android.support.v4.view.ViewPager xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/promotionheader"
tools:context=".Promotions"></android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dip"
android:layout_weight="1"
android:gravity="center"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
android:orientation="horizontal">
<ImageButton
android:id="#+id/btnStores"
style="?android:attr/imageButtonStyle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#color/colorPrimary"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:onClick="startSelectStore"
android:layout_gravity="center_horizontal|center"
android:src="#drawable/btn_home" />
<ImageButton
android:id="#+id/btnCoupons"
style="?android:attr/imageButtonStyle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:background="#color/colorPrimary"
android:onClick="startCouponActivity"
android:layout_gravity="center_horizontal|center"
android:src="#drawable/btn_coupon" />
<ImageButton
android:id="#+id/btnNotifications"
style="?android:attr/imageButtonStyle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:background="#color/colorPrimary"
android:onClick="startNotificationActivity"
android:layout_gravity="center_horizontal|center"
android:src="#drawable/btn_notification" />
<ImageButton
android:id="#+id/btnAbout"
style="?android:attr/imageButtonStyle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="10dp"
android:background="#color/colorPrimary"
android:onClick="startAboutActivity"
android:layout_gravity="center_horizontal|center"
android:src="#drawable/btn_about" />
</LinearLayout>
</RelativeLayout>
Promotions.java
public class Promotions extends AppCompatActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
ArrayList<String> shopList;
// TabHost tabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.promotions);
LayoutInflater layoutInflater = LayoutInflater.from(this);
View customActionBar = layoutInflater.inflate(R.layout.actionbar_promotion, null);
//-- Set Custom icon in ActionBar
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(customActionBar);
ImageButton ibItem1 = (ImageButton) customActionBar.findViewById(R.id.imgBtnSettings);
ibItem1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Promotions.this, SelectStore.class));
}
});
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//View customActionBar1 = layoutInflater.inflate(R.layout.actionbar_promotion_tab, null);
//actionBar.setCustomView(customActionBar1);
actionBar.invalidateOptionsMenu();
//-- Get value from intent
Intent intent = getIntent();
shopList = (ArrayList<String>) intent.getSerializableExtra("selectedStoreList");
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab().setText(shopList.get(i)).setTabListener(this));
}
}
public void startSelectStore(View view) {
Intent intent = new Intent(Promotions.this, SelectStore.class);
startActivity(intent);
}
public void startCouponActivity(View view) {
Intent intent = new Intent(Promotions.this, Coupons.class);
startActivity(intent);
}
public void startNotificationActivity(View view) {
Intent intent = new Intent(Promotions.this, Notifications.class);
startActivity(intent);
}
public void startAboutActivity(View view) {
Intent intent = new Intent(Promotions.this, AboutStore.class);
startActivity(intent);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (position) {
case 0:
fragment = new PromotionFragment();
args.putInt("fragNum", 1);
fragment.setArguments(args);
break;
case 1:
fragment = new PromotionFragment();
args.putInt("fragNum", 2);
fragment.setArguments(args);
break;
case 2:
fragment = new PromotionFragment();
args.putInt("fragNum", 3);
fragment.setArguments(args);
break;
case 3:
fragment = new PromotionFragment();
args.putInt("fragNum", 4);
fragment.setArguments(args);
break;
case 4:
fragment = new PromotionFragment();
args.putInt("fragNum", 5);
fragment.setArguments(args);
break;
case 5:
fragment = new PromotionFragment();
args.putInt("fragNum", 6);
fragment.setArguments(args);
break;
case 6:
fragment = new PromotionFragment();
args.putInt("fragNum", 7);
fragment.setArguments(args);
break;
case 7:
fragment = new PromotionFragment();
args.putInt("fragNum", 8);
fragment.setArguments(args);
break;
case 8:
fragment = new PromotionFragment();
args.putInt("fragNum", 9);
fragment.setArguments(args);
break;
case 9:
fragment = new PromotionFragment();
args.putInt("fragNum", 10);
fragment.setArguments(args);
break;
}
return fragment;
}
#Override
public int getCount() {
if (shopList.isEmpty()) {
return 0;
} else {
return shopList.size();
}
}
}
}
My UI looks like
I want Promotions & Events to be on top of ALL Stores
Someone pls help...
you can try this :---
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Dashboard">
<!-- our toolbar -->
<LinearLayout
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:alpha="3"
android:background="#5d4292"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/menu"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="left|center_vertical"
android:paddingLeft="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/menu_icon" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/search"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:paddingRight="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/search_icon" />
</LinearLayout>
</LinearLayout>
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:alpha="3"
android:background="#5d4292"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabLayout" />
</RelativeLayout>

Categories

Resources