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).
Related
I am sorry on the duplicate question but I didn't get answer for my problem.
I create app with TabActivity and also trying to replace one fragment from fragment itself, I read in https://developer.android.com/training/basics/fragments/fragment-ui.html how to do it and i created interface in my fragment that i want to be replace with another,
I implement the interface in my MainActivity and still when running my app it show me container itself.
here is my code:
Main Activity:
public class MainActivity extends FragmentActivity implements New2.OnReplaceFragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static MainActivity instance = null;
public static MainActivity getInstance(){
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
instance = this;
}
#Override
public void onReplaceFragment(Class fragmentClass) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container,fragment);
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
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() {
}
#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;
}
}
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:
// New1 tab1 = new New1();
return New1.newInstance();
case 1:
return New2.newInstance();
case 2:
return New3.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
my fragment that I want to replace
Fragment:
public class New2 extends Fragment {
TextView name;
Button change;
ImageView image1;
Animation anime;
private OnReplaceFragment dataPasser;
public static New2 newInstance(){
New2 fragment = new New2();
return fragment;
}
public New2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new2, container, false);
name = (TextView) rootView.findViewById(R.id.nameTt);
change = (Button) rootView.findViewById(R.id.changeBtn);
image1 = (ImageView) rootView.findViewById(R.id.image1);
anime = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.zoom);
change.setOnClickListener(changeName);
return rootView;
}
View.OnClickListener changeName = new View.OnClickListener() {
#Override
public void onClick(View view) {
image1.startAnimation(anime);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run(){
dataPasser.onReplaceFragment(Result.class);
}
},1000);
}
};
public interface OnReplaceFragment {
public void onReplaceFragment(Class fragmentClass);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
dataPasser = (OnReplaceFragment) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString() + " must implement onDataPass");
}
}
}
the fragment that i want to display
public class Result extends Fragment {
TextView textView;
Button btnBack;
public static Result instance = null;
public static Result getInstance(){
return instance;
}
public Result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_result, container, false);
textView = (TextView) v.findViewById(R.id.text11);
btnBack = (Button) v.findViewById(R.id.btnBack);
textView.setText("working!!");
Toast.makeText(getActivity().getApplicationContext(),"working",Toast.LENGTH_LONG).show();
return v;
}
}
Main Activity XML:
<?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.hercules.tadhosttutrial.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:background="#color/red"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
New2 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"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/changeBtn"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:text="change"/>
<ImageView
android:id="#+id/image1"
android:background="#drawable/icon_complete"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
Result 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/colorAccent"
tools:context="com.example.hercules.tadhosttutrial.Result">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"/>
<TextView
android:id="#+id/text11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WORKING"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="70dp"
/>
</RelativeLayout>
What i mean, is making MainActivity as a main container for all fragments, either with tabs or just a regular fragment,
1- Main Activity XML: remove ViewPager, add a FrameLayout instead (use same id)
2- Create new fragment TabsFragment with this 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"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
3- Move initializing SectionsPagerAdapter and ViewPager from main activity to TabsFragment:
this part:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
and this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
4- I think moving SectionsPagerAdapter class in a new file is better too.
now if you want default view for app to be the tabs, then in MainActivity at onCreate() show TabsFragment by calling your method:
onReplaceFragment(TabsFragment.class);
now every thing should work fine, because the idea here is to replace the fragment displayed in main activity with another one
in this case TabsFragment, Result, and New2
not to replace viewpager fragments (because as i told you this is managed via the adapter) not by calling replace()
you may need to play around this, it's not a final code, just something to give you idea about it.
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 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();
}
I'm trying to implement a base activity with DrawerLayout so I can extend it to other activities.
I used the default Drawer Application in the Eclipse wizard and the help of these questions: Q1, Q2, and for some reason I get an inflate exception when I launch the app.
public class BaseActivity 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;
private DrawerLayout mDrawerLayout;
private FrameLayout mFrameLayout;
#Override
public void setContentView(int layoutResID) {
mDrawerLayout = (DrawerLayout) getLayoutInflater().inflate(
R.layout.activity_base, null);
mFrameLayout = (FrameLayout) mDrawerLayout.findViewById(R.id.container);
getLayoutInflater().inflate(layoutResID, mFrameLayout, true); /* Exception Here */
super.setContentView(mDrawerLayout);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, mDrawerLayout);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (position) {
case 0:
fragmentManager.beginTransaction()
.replace(R.id.container, new AllCategoriesFragment()).commit();
break;
case 1:
fragmentManager.beginTransaction()
.replace(R.id.container, new AllRecipesFragment()).commit();
break;
}
}
activity_base.xml
<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.yonivy.cookpad.app.BaseActivity" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/navigation_drawer"
android:name="com.yonivy.cookpad.app.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>
AllCategoriesFragment.java
public class AllCategoriesFragment extends Fragment {
private ArrayList<Category> allCategories;
private CategoriesAdapter cAdapter;
private ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_all_categories, container, false);
lv = (ListView) view.findViewById(R.id.mList);
displayAllCategories();
return view;
}
Sample extended class
public class RecipeActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
// ...
}
I'm encountering slow/laggy behaviour when swithcing between frgaments using a drawerlayout. I've read up here on stackoverflow and elsewhere regarding solving this issue and a major piece of advice e.g. as seen here is to populating bits of fragment related views elsewhere hence my question of how best can one do the populating part outside of onCreateView() to avoid the laggy behaviour.
Any help is appreciated.
My code is as follows:
My main activity below:
/*! Main activity class */
public class MainActivity extends ActionBarActivity implements FragListener {
/** Private vars */
private DrawerLayout drawerLayout;
private ListView lvDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private CharSequence drawerTitle;
private CharSequence title;
private DrawerLayoutAdapter drawerLayoutAdapter;
private List<DrawerLayoutDrawer> lvDrawerLayoutData;
/** Public vars */
public static String TAG = "MainActivity";
public MainActivity mainActivity;
public Display display;
public Typeface officialBoldFont, officialRegularFont;
public TextView actionBarTView, tvActionBarTitle = null;
public Fragment fragment;
//!<
public MainActivity() {
}
//!<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// getTitle() is part of Activity
title = drawerTitle = getTitle();
// Obtain the normal device display area
display = getWindowManager().getDefaultDisplay();
// Set official font
officialRegularFont = Typeface.createFromAsset(this.getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(this.getAssets(), "square721extendedbold.ttf");
// Show action bar
getSupportActionBar().show();
// Inflate the custom action bar
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mCustomActionView = inflator.inflate(R.layout.actionbar_layout, null);
tvActionBarTitle = (TextView) mCustomActionView.findViewById(R.id.tv_action_bar_title);
tvActionBarTitle.setTypeface(officialBoldFont);
tvActionBarTitle.setTextColor(Color.parseColor("#000000"));
tvActionBarTitle.setTextSize(14.5f);
getSupportActionBar().setCustomView(mCustomActionView);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xffFFCC00));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
// Inflate and customise the drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setDrawerShadow(new ColorDrawable(0xffFF0000), GravityCompat.START);
drawerLayout.setBackgroundResource(R.drawable.bgnd_drawerlayout_default);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
// Inflate and customise the drawer layout list and drawer layout adapter
lvDrawerLayout = (ListView) findViewById(R.id.lv_drawer);
lvDrawerLayout.setDividerHeight(2);
// Below is the listview's bgnd and is different from bgnd_lv_item_drawerlayout.xml which is the bgnd for the items in this LV
lvDrawerLayout.setBackgroundResource(R.drawable.bgnd_lv_drawerlayout_default);
lvDrawerLayoutData = new ArrayList<DrawerLayoutDrawer>();
lvDrawerLayoutData.add(new DrawerLayoutDrawer("ADMINISTRATION", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("FINANCE CALCULATOR", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("EXIT", R.drawable.ic_test));
drawerLayoutAdapter = new DrawerLayoutAdapter(this, R.layout.lv_layout_drawer, lvDrawerLayoutData, officialRegularFont, officialBoldFont);
lvDrawerLayout.setAdapter(drawerLayoutAdapter);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Call starting fragment
if (savedInstanceState == null) {
callStartingFrag(0);
}
}
//!< Call starting fragment
public void callStartingFrag(int position) {
Bundle args = new Bundle();
fragment = new FragmentOne();
args.putString(" ", lvDrawerLayoutData.get(position).getItemName());
args.putInt(" ", lvDrawerLayoutData.get(position).getImgResID());
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
//!< Enable drawer layout
public void enableDrawerLayout() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
//!< Set custom action bar title
public void setActionBarTitle(String title){
tvActionBarTitle.setText(title);
}
//!< Return MainActivity object
public MainActivity getMainActivity() {
mainActivity = new MainActivity();
return mainActivity;
}
//!< This hook is called whenever an item in your options menu is selected. . The action bar home/up action should open or close the drawer. ActionBarDrawerToggle will take care of this.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
//!< Sync the toggle state after onRestoreInstanceState has occurred. Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
//!< Pass any configuration change to the drawer toggles. This method should always be called by your Activity's onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
//!< Call respective fragment
public void selectItem(int position) {
switch (position) {
case 0:
fragment = new FragmentTwo();
break;
case 1:
fragment = new FragmentThree();
break;
case 2:
finish();
break;
default:
break;
}
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
}
Drawer layout code:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/lv_drawer"
android:layout_width="240dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#000000"/>
</android.support.v4.widget.DrawerLayout>
Drawer layout listview laout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:id="#+id/itemLayout">
<TextView
android:id="#+id/tv_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Action bar layout code:
<?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"
android:background="#android:color/transparent" >
<TextView
android:id="#+id/tv_action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textSize="15dp"
android:maxLines="1"
android:ellipsize="end"/>
</RelativeLayout>
1st fragment code:
public class FragmentOne extends Fragment {
ImageView ivIcon;
TextView tvAgentID;
public Typeface officialBoldFont, officialRegularFont;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_one, container, false);
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag one list item 1", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragOneClickListener());*/
//
officialRegularFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedbold.ttf");
tvAgentID = (TextView) view.findViewById(R.id.tv_agentid);
tvAgentID.setText("TESTING 1 2 3");
tvAgentID.setTypeface(officialBoldFont);
tvAgentID.setTextColor(Color.BLACK);
tvAgentID.setBackgroundColor(Color.WHITE);
tvAgentID.setTextSize(25f);
return view;
}
}
1st fragment layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000">
<LinearLayout
android:id="#+id/ll_innerloginlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp"
android:padding="20dp">
<TextView
android:id="#+id/tv_agentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
2nd fragment code below:
public class FragmentTwo extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
private List<DrawerLayoutDrawer> dataList;
public FragmentTwo()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_two, container, false);
//
((MainActivity) getActivity()).setActionBarTitle("Test screen 2");
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag two list item 2", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragTwoClickListener());*/
ivIcon=(ImageView)view.findViewById(R.id.frag2_icon);
tvItemName=(TextView)view.findViewById(R.id.frag2_text);
tvItemName.setText("TESTING FRAG TWO");
tvItemName.setTextSize(45f);
tvItemName.setTextColor(Color.RED);
tvItemName.setBackgroundColor(Color.BLACK);
return view;
}
}
2nd fragment XML code:
<?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"
android:orientation="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag2_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag2_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="200dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="12dp"
android:paddingBottom="0dp"/>
</LinearLayout>
3rd fragment code:
public class FragmentThree extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentThree()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_three, container, false);
ivIcon=(ImageView)view.findViewById(R.id.frag3_icon);
tvItemName=(TextView)view.findViewById(R.id.frag3_text);
tvItemName.setText("TESTING FRAG THREE");
return view;
}
}
3rd fragment XML code:
<?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"
android:orientation="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag3_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag3_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
1st fragment listener:
public class FragOneClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragOneSelectItem(position);
}
}
2nd fragment listener:
public class FragTwoClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragTwoSelectItem(position);
}
}