I just started an android app that using Drawer Layout. I tried many tutorials to change the layout by clicking the leftbar items.
Here is my code.
public class IndexPageActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index_page);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
ft.replace(R.id.container, PlaceholderFragment.newInstance(position + 1));
ft.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = "Inbox";
break;
case 2:
mTitle = "Completed Task";
break;
case 3:
mTitle = "Settings";
break;
case 4:
mTitle = "Change Password";
break;
case 5:
mTitle = "Logout";
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_background));
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
//getMenuInflater().inflate(R.menu.index_page, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
/**
* 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";
/**
* 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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_index_page, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((IndexPageActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
And my XML Page is :
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.exactsystm.exactsystem.IndexPageActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.exactsystm.exactsystem.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" android:textColor="#ff00" />
</android.support.v4.widget.DrawerLayout>
This is code is generated by Android studio by default when I create a new Navigation Drawer Activity.
This working finely such as the swiping. but when I select a tab of Navigation It does not going to any sections.
How can i solve this issue ?
You should just put a switch statement into the onNavigationDrawerItemSelected method:
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment = null;
switch(position) {
default:
case 0:
fragment = new MyFragment1();
break;
case 1:
fragment = new MyFragment2();
break;
}
getFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Related
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.
Hi I'm new to programming and android studio, I am having trouble adding a ListView in my Java Class Fragment after I already set the class up for a Navigation Drawer Fragment. I have successfully created an app that navigates through the different fragments but once a fragment is selected the ListView I set up in the xml layout does not appear. What I would like my app to do is have a navigation drawer that takes you to different workout types (i.e. gym workouts, calisthenics workouts) then once you select the type of workout for the Navigation Drawer it will open a ListView of all the workouts available to that type. I don't know how to implement a List view in a Navigation Drawer Fragment. My code is provided below. Some of my code is below.
If anyone would help me with this it will be much appreciated!
-----activity_main.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" android:background="#fffdfd">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/home_page"/>
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.teamdnafitness.myapp.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
--One of my fragments.xml---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/calList"></ListView>
</LinearLayout>
---MY MainActivity.java---
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
if(position == 0){
fragmentManager.beginTransaction()
.replace(R.id.container, gymWorkoutsFragment.newInstance())
.commit();
} else if(position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, calisthenicsWorkoutsFragment.newInstance())
.commit();
} else if(position == 2){
fragmentManager.beginTransaction()
.replace(R.id.container, motivationalVideosFragment.newInstance())
.commit();
}
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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";
/**
* 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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
--My Calisthenics Java Class--
public class calisthenicsWorkoutsFragment extends Fragment{
public static calisthenicsWorkoutsFragment newInstance(){
calisthenicsWorkoutsFragment fragment = new calisthenicsWorkoutsFragment();
return fragment;
}
public calisthenicsWorkoutsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calisthenics_workouts, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
I have the layout for the activity:
<fragment
android:name="com.myapp.fragment1"
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment1" />
<fragment
android:name="com.myapp.listfragment1"
android:id="#+id/fragment2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
The first fragment (fragment1) extends Fragment, whilst the second fragment extends ListFragment. I don't have a layout for the listfragment.
The activity code is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
}
An exception is thrown on setContentView:
Error inflating class fragment
The ListFragment code is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyListAdapter(getActivity(), prices));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setDivider(null);
}
What is the correct way to have multiple fragments in an activity?
You can do it by using SectionsPagerAdapter (Swipe View) or by NavigationDrawer (Navigation drawer). I have used swipe view for one of my applications. Here is the codes.
MainActivity.java
public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// 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);
}
});
//Getting icons in icons veriable
final int[] ICONS = new int[]{
R.drawable.chat,
R.drawable.friends,
R.drawable.profile,
};
// 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()
.setIcon(getResources().getDrawable(ICONS[i])).setTabListener(this));
}
}
#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) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#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 index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new ChatFragment();
case 1:
return new FriendsFragment();
// Games fragment activity
//return new ProfileFragment();
case 2:
// Movies fragment activity
//return new FriendsFragment();
return new ProfileFragment();
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.chat_tab).toUpperCase(l);
case 1:
return getString(R.string.friends_tab).toUpperCase(l);
case 2:
return getString(R.string.profile_tab).toUpperCase(l);
}
return null;
}
}
/**
* 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";
/**
* 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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
FriendsFragment.java
public class FriendsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_friends, container, false);
return rootView;
}
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/pager"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" />
fragment_main.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
fragment_friends.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">
<TextView
android:id="#+id/email_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/friends_tab"
android:layout_gravity="center"
android:gravity="center"/>
</LinearLayout>
This is just a sample code of my project. You can use your own code for java or xml. Here i tried to show how to call the fragments in your MainActivityusing swipe view. Hope it helps.
I'm building an app with MainActivity which extends ActionBarActivity and inplemented with NavigationDrawerFragment.NavigationDrawerCallbacks and has an ActionBar i want to have with any tabs. after runing project i get this error and alert me has stopped:
Caused by: java.lang.ClassCastException: android.support.v4.widget.DrawerLayout cannot be cast to android.support.v4.view.ViewPager
at ir.tsms.MainActivity.onCreate(MainActivity.java:43)
i want to have MenuSlide inside Tab on MainActivity
My code:
package ir.tsms;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.*;
import java.util.Locale;
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks, ActionBar.TabListener {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.pager));
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager); /*<-- THIS LINE HAS ERROR */
mViewPager.setAdapter(mSectionsPagerAdapter);
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++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* 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";
/**
* 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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
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);
}
public int getCount() {
// Show 3 total pages.
return 3;
}
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
MainActivity Layout:
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ir.tsms.MainActivity" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/navigation_drawer"
android:name="ir.tsms.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
how to resolve this problem?
your problem:
casting android.support.v4.widget.DrawerLayout to viewpager. in that line you are finding navigationdrawer but you cast it to view pager, you must change it to navigationDrawer or put view pager in your layout and find that.
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ir.tsms.MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
</android.support.v4.view.ViewPager>
<fragment
android:id="#+id/navigation_drawer"
android:name="ir.tsms.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
I am trying to change the layout, or inflate the layout, of the main activity to the About activity when one of the items is clicked in the navigation drawer.
This is how my main activity looks
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment holderFragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
switch (sectionNumber) {
case 1:
bundle.putInt(ARG_SECTION_NUMBER, 05);
break;
case 2:
fragment = new About();
bundle.putInt(ARG_SECTION_NUMBER, 16);
break;
case 3:
bundle.putInt(ARG_SECTION_NUMBER, 1991);
break;
}
holderFragment.setArguments(bundle);
return holderFragment;
}
public PlaceholderFragment() {
}
#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(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
my main activity .xml looks like this
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="#+id/navigation_drawer"
android:name="com.projectname.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
I have a fragment_about.xml
and this is how the about class looks.
public class About extends Fragment {
public About(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about, container, false);
return rootView;
}
}
this is how my fragment_main.xml looks like
<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"
tools:context="com.projectname.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
the navigation drawer works fine but it only changes a text view, i cant figure out how to change the entire layout from the main activity to the about activity on the click of an item in the drawer.
i Just don't know what to do, every time i do something i get an error.
First of all you should extend the FragmentActivity class by your MainActivity. Then in NavigationDrawer click listener do this:
RelativeLayout l = (RelativeLayout) findViewById(R.id.container);
FragmentManager manager = getSupportFragmentManager();
About fragment = new About();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
And remove from fragment_main (if you not gonna use next like one deeper fragment).