ActionBarSherlock and FragmentTabsPager - java

As a lot of people have been doing so far, I'm implementing the FragmentTabsPager into my app, which is using ActionBarSherlock 4.0. However, I'm lost.
Fragments, and all of Google's little ideas, plans and methods surrounding it, are confusing me. If anyone could take a look at my code and walk me through this, providing help in making it work, I would thank them a thousand times :D.
I have another project with a sort-of beginning for a ViewPager, but the Tabs just mix better, especially with them being in the ActionBar on landscape and tablets.
My code is all zipped up and ready to go over here:
http://dl.dropbox.com/u/21807195/Antonius%20College%202.zip
Thanks in advance!

I will show you my code that has a ViewPager, TabListener, and system of Fragments linked to each tab. It implements ABS, but as of yet, still crashes on Gingerbread and lower (works beautifully on ICS, though):
import java.util.ArrayList;
import library.DatabaseHandler;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
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.view.ViewPager.OnPageChangeListener;
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
Log.v(TAG, (String)bar.getTabAt(0).getText());
}
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
public int getCount() {
return mTabs.size();
}
public SherlockFragment getItem(int position) {
TabInfo info = mTabs.get(position);
return (SherlockFragment)Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
//Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
}
And here is what one fragment looks like:
package com.davekelley.polling;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MilitaryFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.militaryfragment, container, false);
}
}
My last note would that my code still has one other issue: individual fragments do not always reload their interface after the user press back (which results in removing the entire app from the screen, regardless which tab/fragment they are on, because I have no backStack). So that's what I'm working through now. I think once I have that sorted, I'll try to figure out why I still don't have Gingerbread execution functioning properly. Either way, I hope looking through this code helps you out.
Here is a fragment with some onClickListeners:
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class LoginFragment extends SherlockFragment {
Button loginButton;
Button registerButton;
Polling activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.loginfragment, container, false);
return v;
}
public void onResume() {
super.onResume();
Log.d("Econ", "onresume");
loginButton = (Button) getActivity().findViewById(R.id.loginButton);
loginButton.setOnClickListener(loginListener);
registerButton = (Button) getActivity().findViewById(R.id.registerButton);
registerButton.setOnClickListener(registerListener);
}
public OnClickListener loginListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(loginButton.getText().toString() == "Log Out") {
activity.loginReport(2);
loginButton.setText(R.string.login);
//Remove user from dB sqllite when I know how
}
else {
Log.v("LoginF", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Logging in...");
LoginTask loginTask = new LoginTask((Polling) getActivity(), progressDialog);
loginTask.execute();
}
}
};
public OnClickListener registerListener = new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Register", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Registering new user...");
RegisterTask registerTask = new RegisterTask((Polling) getActivity(), progressDialog);
registerTask.execute();
}
};
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (Polling) activity;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onStart() {
super.onStart();
Log.d("Econ", "onstart");
}
public void onPause() {
super.onPause();Log.d("Econ", "onpause");
}
public void onStop() {
super.onStop();
Log.d("Econ", "onstop");
}
public void onDestroyView() {
super.onDestroyView();
Log.d("Econ", "ondestroyview");
}
public void onDestroy() {
super.onDestroy();
Log.d("Econ", "ondestroy");
}
public void onDetach() {
super.onDetach();
Log.d("Econ", "ondetach");
}
}
The loginTask objects that you see are actually classes that extend ASyncTask - they handle connecting to my server and registering/logging in.
I thought it would be helpful to add in one bit more of code. This is another one of my fragments, like LoginFragment, but it inflates a UI a little differently. Eventually, what you see in the while loop below, will head into an ASyncTask to acquire each question from the server, rather than the dummy string array you see:
public class EconFragment extends SherlockFragment {
private TableLayout questionContainer;
int pos = 0;
private String[] titles = {"The first title ", "hallo1","hallo2", "hallo3",
"hallo4", "hallo5","hallo6", "hallo7","hallo8", "hallo9"};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v("Econ", "onCreateView");
View v = inflater.inflate(R.layout.econfragment, container, false);
questionContainer = (TableLayout) v.findViewById(R.id.questionContainer);
//bs
int leftMargin=5;
int topMargin=5;
int rightMargin=5;
int bottomMargin=5;
while (pos < 10) {
View question = inflater.inflate(R.layout.question, null);
question.setId(pos);
TextView title = (TextView) question.findViewById(R.id.questionTextView);
title.setText(titles[pos]);
Button charts = (Button) question.findViewById(R.id.chartsButton);
charts.setId(pos);
charts.setOnClickListener(chartsListener);
TableRow tr = (TableRow) question;
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
trParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(trParams);
Log.v("econ", "while loop");
questionContainer.addView(tr);
pos++;
}
pos = 0;
return v;
}

I have ported the FragmentTabsPager Activity and associated Fragments from "Support4Demos" (Android Support library sample) to use ActionBarSherlock and true ActionBar Tabs. The sample includes an Activity that uses both a ViewPager and Tabs to switch between Fragments. The Fragments contain three kinds of ListViews. I've tested it from ICS down to Eclair (2.1). You can browse or download the code at http://code.google.com/p/sherlock-demo/.

Related

Fragment translation and phone orientation bug

Phone's orientation and fragment translation bug.
I have an activity and some fragments. The first fragment comes right away over the activity with a logo and after 3 seconds the second fragment translates over. The problem is if I change the orientation of the phone, the 1st fragment reappears with the same delay and same behavior as I start the app.
MainActivity:
package com.mainpackage.pinbook;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.mainpackage.pinbook.com.autentification.LoginFragment;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container , new MainScreen());
fragmentTransaction.commit();
}
}
MainScreen:
package com.mainpackage.pinbook;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.mainpackage.pinbook.com.autentification.*;
public class MainScreen extends Fragment{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_screen , container , false);
}
private TextView entry_text;
public static final String TAG = MainScreen.class.getSimpleName();
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
slide();
}
}, 3000);
}
private void slide(){
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(0,R.anim.slide_in_left);
fragmentTransaction.replace(R.id.main_container , new LoginFragment());
fragmentTransaction.commit();
}
#Override
public void onStop() {
super.onStop();
((AppCompatActivity)getActivity()).getSupportActionBar().show();
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
}
}
The second fragment can be blank.
What I want is simply to remain on the current fragment when I change the phone's orientation
When the device rotates onCreate() gets called again.
Wrap your fragment transaction in onCreate() like so:
if (savedInstanceState == null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container , new MainScreen());
fragmentTransaction.commit();
}
This will prevent the first fragment from being put back on top when you rotate.

Android Studio: Unable to remove fragment

I'm trying to remove a fragment and it's not working.
I've been checking with logcat and it's noticing that the button's been clicked and that message is being passed to the main activity. I assume there's something wrong with my code but I can't figure out what that is. Would appreciate some help.
MainMenu.java
package com.example.android.learninstrumentation;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainMenu extends AppCompatActivity implements MainMenuStFrag.MainMenuStFragListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
//Create a new Fragment to be placed in the Activity layout
Fragment menuSiFragment = new MainMenuSiFrag();
Fragment menuStFragment = new MainMenuStFrag();
//Add the fragment to the 'fragment_container' layout
getSupportFragmentManager().beginTransaction().add(R.id.fragment_type_si_container, menuSiFragment).commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_type_st_container, menuStFragment).commit();
}
//The user clicked 'expand' from MainMenuStFrag. Remove MainMenuSiFrag.
public void onExpandClick () {
Log.i("MainMenu", "Click message received");
Fragment oldFragment = new MainMenuSiFrag();
getSupportFragmentManager().beginTransaction().remove(oldFragment).addToBackStack(null).commit();
}
public void onCheckboxClick() {
}
}
MainMenuStFrag.java
package com.example.android.learninstrumentation;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
public class MainMenuStFrag extends Fragment implements View.OnClickListener{
MainMenuStFragListener mCallback;
//Inflate the layout and set buttons for this fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Store the Fragment in the mainMenu variable
View mainMenu = inflater.inflate(R.layout.main_menu_st_fragment, container, false);
//Define the buttons and set onClickListeners
ImageView expand = mainMenu.findViewById(R.id.mainMenu_imageView_SelectTopics);
expand.setOnClickListener(this);
CheckBox checkBox = mainMenu.findViewById(R.id.mainMenu_CheckBox_SelectAllTopics);
checkBox.setOnClickListener(this);
return mainMenu;
}
//Interface for communication with container Activity
public interface MainMenuStFragListener {
void onExpandClick();
void onCheckboxClick();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
//This makes sure the container Activity has implemented the callback interface.
// If not, it throws an exception.
try {
mCallback = (MainMenuStFragListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
//onClick actions
#Override public void onClick(View v) {
switch (v.getId()) {
//Remove the other 'type' item
case R.id.mainMenu_imageView_SelectTopics:
Log.i("MainMenuStFrag", "Topics>Expand=Clicked");
mCallback.onExpandClick();
break;
case R.id.mainMenu_CheckBox_SelectAllTopics:
mCallback.onCheckboxClick();
break;
}
}
}
MainMenuSiFrag.java
package com.example.android.learninstrumentation;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainMenuSiFrag extends Fragment {
//Inflate the layout for this fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainMenu = inflater.inflate(R.layout.main_menu_si_fragment, container, false);
return mainMenu;
}
}
You have created new instance of Fragment for remove Fragment
public void onExpandClick () {
Log.i("MainMenu", "Click message received");
Fragment oldFragment = new MainMenuSiFrag();
getSupportFragmentManager().beginTransaction().remove(oldFragment).addToBackStack(null).commit();
}
instead on that Find a fragment and remove it from container
Fragment oldFragment=getSupportFragmentManager().findFragmentById(R.id.fragment_type_si_container);
if(oldFragment!=null && oldFragment instanceof MainMenuSiFrag)
{
getSupportFragmentManager()
.beginTransaction().
remove(oldFragment).commit();
}

implements TopSectionFragment Cannot resolve symbol android studio

public class MainActivity extends AppCompatActivity implements
TopSectionFragment.TopSectionListener {
When I try to implement the TopSectionFragment the writing goes red and, then it says Cannot resolve symbol when my mouse goes over it.
This is all happening in Android Studio.
My MainActivity.java looks like this:
package com.example.danielhunter.fragments;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;`
public class MainActivity extends AppCompatActivity
implements TopSectionFragment.TopSectionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
My TopSectionFragment.java looks liks this:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.ViewGroup;
import android.view.View;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import com.example.danielhunter.fragments.R;
public class TopSectionFragment extends Fragment {
private static EditText topTextInput;
private static EditText bottomTextInput;
TopSectionListener activityCommander;
public interface TopSectionListener{
public void createMeme(String top,String bottom);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
activityCommander = (TopSectionListener) activity;
}catch (ClassCastException e){
throw new ClassCastException(activity.toString());
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment, container, false);
topTextInput = (EditText) view.findViewById(R.id.topTextInput);
bottomTextInput = (EditText) view.findViewById(R.id.bottomTextInput);
final Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
buttonClicked(v);
}
}
);
return view;
}
// calls this when the button is clicked
public void buttonClicked(View view){
activityCommander.createMeme(topTextInput.getText().toString(), bottomTextInput.getText().toString());
}
}
In order for a class to correctly implement an interface, it must include implementations of ALL the methods defined in the interface. In your case, MainActivity would need to have a method with the signature void createMeme(String top,String bottom) in order for this to compile.

cannot resolve method show(android.support.v4.app FragmentManager,java.lang.string)

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by jamie on 9/12/2015.
*/
public class PlayersFragment extends DialogFragment {
ListView lv;
String[] players = {"arteta", "costa", "reid", "degea", "rooney", "terry"};
int[] images = {R.drawable.arteta, R.drawable.costa, R.drawable.reid, R.drawable.degea,
R.drawable.rooney, R.drawable.terry};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog, container, false);
//initialize listview
lv = (ListView) rootView.findViewById(R.id.listView1);
//set dialog title
getDialog().setTitle("Soccer SuperStars");
//create adapter obj and set list view to it
Adapter adapter = new Adapter(getActivity(), players, images);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Toast.makeText(getActivity(), players[pos], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Trying to create a ListView fragment in android studio and getting
error
cannot resolve method show(android.support.v4.app
FragmentManager,java.lang.string)
the error is on the p.show(fm,"Players Fragment) underlined in red, tried to resolve this but getting nowhere, i would really appreciate a solution to this! thank you
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
Button showBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentManager fm =getSupportFragmentManager();
final PlayersFragment p=new PlayersFragment();
showBtn=(Button)findViewById(R.id.button1);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
p.show(fm,"Players Fragment"); //error is here
}
});
}
}
I suppose you are using android.app.DialogFragment and not android.support.v4.app.DialogFragment. Just extend PlayersFragment from support library's android.support.v4.app.DialogFragment. Or, if you are not targeting old devices, you can change getSupportFragmentManager() to getFragmentManager()
You have to import android.support.v4.app.DialogFragment on the class PlayersFragment and then change getSupportFragmentManager() to getFragmentManager().

Android Navigation draw re-loading fragment whenever closed

I am trying to convert all my code from activities to fragments in order to use a navigation drawer and eventualy some sliding tabs.
Currently I have a semi working navigation drawer that opens and displays a list. BUt I am new to fragments and am confused because it seems to reload my first fragment everytime I close the navigation drawer and do not select anything.
MainDrawer.java :
package com.beerportfolio.beerportfoliopro;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Mike on 1/3/14.
*/
public class MainDraw extends FragmentActivity {
final String[] data ={"Statistics","two","three"};
final String[] fragments ={
"com.beerportfolio.beerportfoliopro.StatisticsPage",
"com.beerportfolio.beerportfoliopro.FragmentTwo",
"com.beerportfolio.beerportfoliopro.FragmentThree"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//todo: load statistics fragment
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main, Fragment.instantiate(MainDraw.this, fragments[pos]));
tx.commit();
}
});
drawer.closeDrawer(navList);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main,Fragment.instantiate(MainDraw.this, fragments[0]));
tx.commit();
}
}
StatisticsPage.java :
package com.beerportfolio.beerportfoliopro;
import android.app.ActionBar;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Mike on 1/3/14.
*/
public class StatisticsPage extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String url = "http://www.beerportfolio.com/app_getStatistics.php?";
String userURLComp = "u=" + userID;
url = url + userURLComp ;
Log.d("basicStats", url);
new getBasicStats(getActivity()).execute(url);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.statistics_pagelayout, container, false);
}
}
The issue is that your DrawerListener is set in your OnClickListener when it shouldn't be:
#Override public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener(
new DrawerLayout.SimpleDrawerListener(){
#Override public void onDrawerClosed(View drawerView){...}
}
);
}
The scope of your pos integer is such that, every time the drawer closes, onDrawerClose thinks that the value of pos hasn't changed. Since there isn't a condition checking that an item was clicked, then the same Fragment is recreated each time the drawer closes (unless you click on a different item).
Set a member boolean to true when an item is clicked and set a member int to its position. Use the boolean to differentiate between an item click and a drawer close:
private boolean mNavItemClicked = false;
private int mNavPosition = 0;
...
#Override protected void onCreate(Bundle savedInstanceState) {
...
navList.setOnItemClickListener(new ListView.OnItemClickListener {
#Override public void onItemClick(AdapterView parent, View view, int position, long id) {
mNavItemClicked = true;
mNavPosition = position;
drawerLayout.closeDrawer(navList);
}
});
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(...) {
public void onDrawerClosed(View view) {
if (mNavItemClicked) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, Fragment.instantiate(MainDraw.this
, fragments[mNavPosition])
.commit();
}
mNavItemClicked = false;
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
If you decide to use the ActionBarDrawerToggle then follow its design guidelines and call through to the Activity callback methods onConfigurationChanged and onOptionsItemSelected.

Categories

Resources