please help me i am new to android.
I can display toast by clicking item in navigation drawer but how can i open new fragment from navigation drawer.
My code in NavigationDrawerFragment is
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new EduAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Toast.makeText(getActivity(), "On click " + position, Toast.LENGTH_LONG).show();
mDrawerLayout.closeDrawer(GravityCompat.START);
Toast.makeText(getActivity(), "On Long click " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(getActivity(), "On long click " + position, Toast.LENGTH_LONG).show();
}
}));
return layout;
}
and in main activity is :
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_appbar);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment =
(NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
}
#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;
}
please help me to open new fragment from drawer as i can only display toast.
i wqas following Slidenerd Material design Video .
Create a class which extends Fragment Activity and then you can open the new fragment as shown below from the new class:
DetailViewFragment f1 = new DetailViewFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_layout, f1).commit();
In your onItemClicked method Navigate to the class created.
Hope this helps you.
On Your RecyclerView's item click you simply have to add the corresponding fragment this way.
getSupportFragmentManager()
.beginTransaction()
.replace(your_container_id,
new YourFragment(), YOUR_FRAGMENT_STRING_TAG)
.commit();
Please keep in mind that for each position click of the recyclerview you will add your fragment in the above way. You can probably use switch cases inside your onItemClick of the recyclerView.
See if it helps you!!! Tell me if you need any other help!!
Create a method and pass the item position in Recylerview's onitemclicklistener
public void changeFragment(int position) {
switch (position) {
case 0:{ getSupportFragmentManager().beginTransaction().replace(R.id.container, calenderFragment).setTransition (FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
break;
}
case 1:{ getSupportFragmentManager().beginTransaction().replace(R.id.container, new PatientProfileFragment()).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
break;
}
}
}
Related
I have a navigation drawer and a fragment that generates a list of products. The problem is that when I click on a product it tryes to find onClick method in base activity not in fragment's java class. Should I implement onClick method in the base activity or is there any way to implement it in fragment's class.
This is product's layout "item_order.xml":
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="orderClick"
android:id="#+id/tOrder"
android:padding="4dp">
....
</RelativeLayout>
Here is the base class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waiter);
//set fragment
OrdersFragment fragment=new OrdersFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
OrdersFragment.wa=this;
}
Here is the fragment:
public class OrdersFragment extends Fragment {
private Database db;
private ArrayList<Order> orders=new ArrayList<Order>();
private OrderAdapter adapter;
private ListView listOrders;
public static WaiterActivity wa;
public OrdersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orders, container, false);
// Inflate the layout for this fragment
db = new Database();
db.createNewOrderListener(this);
ListView listOrders = (ListView) view.findViewById(R.id.ordersList);
adapter = new OrderAdapter(this.getContext(), R.layout.item_order, orders);
listOrders.setAdapter(adapter);
return view;
}
I think you are talking about list view item selection.
Firstly remove onClick from you xml. Create a function orderClick in you base activity and Then in you fragment add onItemClick listener to your list view.
listOrders.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (getActivity() instanceof "your base activity"){
(("your base activity")getActivity()).orderClick();
}
}
});
You should call activity method for taking action by calling it in your fragment class and pass the itemIndex of item that has been called.
use setOnItemClickListener in your activity, and call the fragments from there only, as:-
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
switch (position) {
case 0:
fragment = new ProgramFragment();
break;
case 1:
fragment = new FeedbackFragment();
break;
case 2:
fragment = new ShareFragment();
break;
case 3:
fragment = new LogOutFragment();
break;
default:
fragment =null;
}
if (fragment != null) {
fragmentManager.beginTransaction().replace(R.id.main_fragment_container, fragment).commit();
}
mDrawerList.setItemChecked(position, true);
drawerLayout.closeDrawer(mDrawerList);
}
});
I have implemented Navigation drawer given in the Android Studio 1.5.1.
I have 5 navigation drawer items with a fragment to each of them. Each Fragment has Share method (Not common).
Inside 1st Navigation drawer item's fragment lets say OldStory Fragment, I am having Swipe view with Viewpager consisting 3 fragments with FragmentStatePagerAdapter. It has Share method.
Problem
- Share Method from Story Fragment is getting called every time even when other fragment is shown on screen. After debugging I came to know that method from Story fragment is getting called.
- If I disable OldStory Fragment then everything works fine.
I am unable to solve this problem. I read so many Question/answers but they are related to Activity and Fragment methods. Please help me to solve this problem.
Note - OldStory fragment has inner class that extends FragmentStatePagerAdapter class. This class creates Many Story Fragments. Other implementation is same.
public class OldStory extends Fragment {
private StoryPagerAdapter storyPagerAdapter;
private InfiniteViewPager viewPager;
SharedPreferences sharedPreferences;
private int TotalCount;
public OldStory() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Notify the system to allow an options menu for this fragment.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_old_story, container, false);
viewPager = (InfiniteViewPager) rootView.findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(0);
sharedPreferences = getActivity().getSharedPreferences(Startup.PreferenceSETTINGS, Context.MODE_PRIVATE);
TotalCount = sharedPreferences.getInt(Startup.StoryCount, 4);
storyPagerAdapter = new StoryPagerAdapter(getFragmentManager());
PagerAdapter wrappedAdapter = new InfinitePagerAdapter(storyPagerAdapter);
viewPager.setAdapter(wrappedAdapter);
viewPager.setCurrentItem(TotalCount-1);
return rootView;
}
public class StoryPagerAdapter extends FragmentStatePagerAdapter {
public StoryPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return Story.newInstance(position+1);
}
#Override
public int getCount() {
return TotalCount;
}
}
}
Story Fragment method Implementation -
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.story, menu);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Refresh:
// We make sure that the SwipeRefreshLayout is displaying it's refreshing indicator
if(!visiblity) {
if (!RefreshLayout.isRefreshing()) {
ErrorLayout.setVisibility(View.GONE);
RefreshLayout.setRefreshing(true);
}
// Start our refresh background task
initiateRequest(Today);
}
return true;
case R.id.Share:
//InShort = sharedPreferences.getString(Startup.InShort, null);
Toast.makeText(getContext(), "Stories", Toast.LENGTH_SHORT).show();
if (InShort!= null && !InShort.isEmpty())
{
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi From Story");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
MainActivity used for switching fragments.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displayView(item.getItemId());
return true;
}
//method to replace Views in ID = content_frame in content_main
public void displayView(int viewID)
{
fragment = null;
title = getString(R.string.app_name);
switch (viewID)
{
case R.id.nav_frag0:
fragment = new OldStory();
title = getString(R.string.story);
viewIsAtHome = true;
break;
case R.id.nav_frag1:
fragment = new Fragment1();
title = getString(R.string.fragment1);
viewIsAtHome = false;
break;
case R.id.nav_frag2:
fragment = new Fragment2();
title = getString(R.string.fragment2);
viewIsAtHome = false;
break;
case R.id.nav_frag3:
fragment = new Fragment3();
title = getString(R.string.fragment3);
viewIsAtHome = false;
break;
case R.id.nav_frag4:
fragment = new Fragment4();
viewIsAtHome = false;
title = getString(R.string.fragment4);
break;
case R.id.nav_share:
fragment = new Fragment5();
title = getString(R.string.fragment5);
viewIsAtHome = false;
break;
}
if (fragment != null)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,fragment);
ft.commit();
}
//set the toolbar title
if(getSupportActionBar() != null)
{
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
I am not sure if it is really the answer to your question, but I noticed one error in your code:
storyPagerAdapter = new StoryPagerAdapter(getFragmentManager());
will not work correctly becasuse you need to use getChildFragmentManager() to manage fragments within fragments.
I was trying to reproduce your issue and wrote this app, which as I understood from the question is copying your app's behaviour:
I've uploaded the source code for it into my Dropbox - feel free to check it out
As you can see, the fragments handle Share button clicks properly.
There's always a chance, that I didn't fully understand your question, but here's how I've done it:
All fragments inflating this menu (but with different onOptionsItemSelected):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
app:showAsAction="always"
android:title="Share" />
</menu>
My SubFragment class (the one I'm using inside ViewPager) in FragmentA:
public class SubFragment extends Fragment {
String msg;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.subfragmnet, container, false);
setHasOptionsMenu(true);
rootView.findViewById(R.id.subfragmentFrameLayout).setBackgroundColor(getArguments().getInt("background"));
msg = getArguments().getString("msg");
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.nav_share) {
Snackbar.make(getView(), "Hello from SubFragment " + msg, Snackbar.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
FragmentA, the first Fragment, which hosts ViewPager and nested Fragments:
public class FragmentA extends Fragment {
PagerAdapter pagerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
Bundle bundle1 = new Bundle();
bundle1.putInt("background", Color.RED);
bundle1.putString("msg", "page 1");
Bundle bundle2 = new Bundle();
bundle2.putInt("background", Color.YELLOW);
bundle2.putString("msg", "page 2");
Bundle bundle3 = new Bundle();
bundle3.putInt("background", Color.BLUE);
bundle3.putString("msg", "page 3");
Fragment[] fragments = {
Fragment.instantiate(getContext(), SubFragment.class.getName(), bundle1),
Fragment.instantiate(getContext(), SubFragment.class.getName(), bundle2),
Fragment.instantiate(getContext(), SubFragment.class.getName(), bundle3),
};
if (pagerAdapter == null) {
pagerAdapter = new PagerAdapter(getChildFragmentManager(), fragments);
}
ViewPager viewPager = (ViewPager)rootView.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
return rootView;
}
}
FragmentB (and pretty much the same FragmentC):
public class FragmentB extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_b, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.nav_share) {
Toast.makeText(getContext(), "Hello from Fragment B", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
Hosting Activity is standard NavigationDrawer Activity with is switching Fragments on Drawer's item click.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
....
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentA.class.getName())).commit();
}
...
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentA.class.getName())).commit();
} else if (id == R.id.nav_gallery) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentB.class.getName())).commit();
} else if (id == R.id.nav_slideshow) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentC.class.getName())).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Let me know, if I understood your question properly!
Anyway, I hope, it helps.
My .java code is :
public class welcome extends Activity
{
Button button1;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private String mTitle = "";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
mTitle = "JAVATECHIG.COM";
getActionBar().setTitle(mTitle);
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
mDrawerList.setClickable(true);
mDrawerList.setTextFilterEnabled(true);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("JAVATECHIG.COM");
Toast.makeText(getApplicationContext(), "Inside onDrawerOpened...", Toast.LENGTH_SHORT).show();
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
Toast.makeText(getApplicationContext(), "Inside ClickListener...", Toast.LENGTH_SHORT).show();
// Currently selected river
mTitle = menuItems[position];
// Creating a fragment object
WebViewFragment rFragment = new WebViewFragment();
// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
rFragment.setArguments(data);
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, rFragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "After ArrayAdapter decraration...", Toast.LENGTH_SHORT).show();
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
}
protected String getUrl(int position) {
switch (position) {
case 0:
return "http://javatechig.com";
case 1:
return "http://javatechig.com/category/android/";
case 2:
return "http://javatechig.com/category/blackberry/";
case 3:
return "http://javatechig.com/category/j2me/";
case 4:
return "http://javatechig.com/category/sencha-touch/";
case 5:
return "http://javatechig.com/category/phonegap/";
case 6:
return "http://javatechig.com/category/java/";
default:
return "http://javatechig.com";
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Also my XML code is:
<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="match_parent" >
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
/>
</android.support.v4.widget.DrawerLayout>
WebViewFragement.java code is:
public class WebViewFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.menus);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
//WebView webView = (WebView)v.findViewById(R.id.webView);
//webView.getSettings().setJavaScriptEnabled(true);
//webView.loadUrl(url);
Toast.makeText(getActivity(),position+" ... "+url,Toast.LENGTH_SHORT).show();
return v;
}
}
.
.
My Question is whenever I run this code and click on any of the side menu option, it is not displaying anything. Means it is not going inside setOnItemClickListener().
I have tried all possible solution posted in this form but, these are not working.
Kindly help.
the error is probably in this line mDrawerList.setOnItemClickListener(new OnItemClickListener()) instead of implementing onItemClickListener implement list_item.setOnItemClickListener(new DrawerItemClickListener());
this is the first application I am creating using a NavigationDrawer. I have a pretty simple question. How do I make the first page in the NavigationDrawer the main one? Also I'm not too familiar with formatting since this is my first time using the drawer so I would appreciate it if someone more familiar could tell me if I am doing it correctly. Right now each page just displays text but eventually it will do more. And one of my questions is how do I make it so that clicking a page in the drawer can open up a new page using a RelativeLayout for example. From my understanding Adapters are only for Views, would I create a completely new activity and call startActivity() in my iteration for the drawerclick? If so, is that efficient? Meaning will it take a long time for the page to load? My main activity is:
public class MainActivity extends Activity {
private String[] mPages;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_layout);
mPages = getResources().getStringArray(R.array.page_titles);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPages));
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment fragment;
if(position == 0){
fragment = new OneFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
else if(position == 1){
fragment = new TwoFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
else if(position == 2){
fragment = new ThreeFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
else if(position == 3){
fragment = new FourFragment();
// Insert the fragment by replacing any existing fragment
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPages[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
public static class OneFragment extends Fragment{
public OneFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("One");
return rootView;
}
}
public static class TwoFragment extends Fragment{
public TwoFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("Two");
return rootView;
}
}
public static class ThreeFragment extends Fragment{
public ThreeFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("Three");
return rootView;
}
}
public static class FourFragment extends Fragment{
public FourFragment(){
}
View rootView;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup contatiner,
Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.drawer_layout,
contatiner, false);
text = (TextView)rootView.findViewById(R.id.text_view1);
text.setText("Four");
return rootView;
}
}
}
I apologize for the lengthy question, but the developer site wasn't helping out too much and I want to make sure I do this correctly the first time so I don't have to go back too much
Whatever you want to show needs to be within the child of the DrawerLayout. In your case, I think you would do a fragment transaction in onCreate() to put whatever fragment you want visible first inside of the content area.
if (savedInstanceState == null) {
fragment = new OneFragment();
// Insert the fragment by replacing any existing fragment
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
You can hold references to these fragments so you don't create a new instance of them each time the user makes a selection. You probably also want to make sure the new selection isn't the same as the current one, or else you will have extra transactions you don't need.
For opening a "new page", you want to use startActivity() and show another activity with it's own layout. Generally speaking, don't be concerned about how long it takes an Activity to load unless you are specifically doing some meaningful work (like loading a bunch of data out of a database).
Lastly, Adapters are specifically for AdapterViews (like ListView) and are an entirely different matter. They are used in conjunction with specific UI components to generate child views for representing potentially large data sets and which can be recycled for efficiency reasons. I suggest you watch The World of ListView if you want more information/clarity about that.
I would like to implement a swipe views into my Sherlock fragments with the drawer menu.
I did it and it seems works fine, owever, there is a minor issue that i can't figure out.
So let's begin with some pices of my code:
MainActivity
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new TestFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Test title" };
// Generate subtitle
subtitle = new String[] { "Test subtitle" };
// Generate icon
icon = new int[] { R.drawable.action_about };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
TestFragment:
public class TestFragment extends SherlockFragment {
ViewPager mViewPager;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.test, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
PagerTabStrip pagerTabStrip = (PagerTabStrip) rootView.findViewById(R.id.pagerTabStrip);
testAdapter titleAdapter = new testAdapter(getFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(0);
return rootView;
}
}
testAdapter
public class testAdapter extends FragmentPagerAdapter {
private String titles[] = new String[]{"View1","View2"};
private Fragment frags[] = new Fragment[titles.length];
public systemAdapter(FragmentManager fm) {
super(fm);
frags[0] = new testSwipe1();
frags[1] = new testSwipe2();
}
#Override
public CharSequence getPageTitle (int position){
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
testSwipe1 and testSwipe2 are the same:
public class testSwipe1 extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.testswipe_layout, container, false);
ImageButton testImage = (ImageButton) rootView.findViewById(R.id.test);
//todo function image
return rootView;
}
}
Ok, the drawer works fine and if i tap on "test title" it inflate the layout with the swipe and i can see the image in the 2 test swipe views.
Owever, if i open back the drawer and tap again on "test title" i can see the swipe views without the images on my swipe fragment layout. If i put the device in landscape and back to portrait, the image on my swipe fragments come back! open drawer -> tap again on test title -> images disappear.... -> landscaper -> portrait -> image back.
The layouts defined are standard for drawer and swipeviews. inside the swipeviews fragments layout there is only an imageview. So the issue must be in the java part but i can't figure out where.
Any helps?
Try this: TestAdapter should implement FragmentStatePagerAdapter instead of FragmentsPagerAdapter. The reason is that the method getItem() is called differently. I had the same problem. Hope this helps.
I have edited the code given in here.
I just change the asyDrawerLayout.java file by implementing OnGestureListener interface with it's methods.
In the onCreate() I have set the gesture to the current context by adding following line.
gd = new GestureDetector(this, this);
Then I have Override the onTouchEvent() as follows
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
//Registering TouchEvent with GestureDetector
return gd.onTouchEvent(event);
}
Then I have changed the onFling() as follows
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
//Defining Sensitivity
float sensitivity = 30;
//Swipe Left Check
if(e1.getX() - e2.getX() > sensitivity && mOpen){
closeDrawer();
return true;
}
//Swipe Right Check
if(e2.getX() - e1.getX() > sensitivity && !mOpen){
openDrawer();
return true;
}
return true;
}
Now it is working with Drawer menu + swipeView.
You can download my edited version from here.