I'm trying to go to a specific fragment and I intialisate this in Activity. But I don't get any error on my screen but on my device, my app is stopped running, he doesn't go in Fragment. What can be the problem? Thanx for you help. Below you find my code:
public class SubCatActivity extends Activity {
int hoofdCat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcat);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new SubCatFragment())
.commit();
}
hoofdCat = Integer.parseInt(getIntent().getStringExtra("hoofdCat"));
}
public int getHoofdCat(){return hoofdCat;}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.info, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
My Fragment:
public class SubCatFragment extends Fragment implements SubCatFragmentInteractionListener {
private SubCatFragmentInteractionListener mListener;
public SubCatFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_subcat, container, false);
ListView lstSubcat = (ListView) rootView.findViewById(R.id.lvSubcat);
ArrayList<String> subcat = new ArrayList<String>();
SubCatActivity activity = (SubCatActivity)getActivity();
int hoofdcat =activity.getHoofdCat();
DBAdapter db = new DBAdapter(getActivity().getBaseContext());
db.open();
Cursor c = db.getAllSubcat(hoofdcat);
if(c.moveToFirst())
{
do{
subcat.add(c.getString(1));
}while (c.moveToNext());
}
db.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, subcat);
lstSubcat.setAdapter(adapter);
lstSubcat.setOnItemClickListener(lstSubcatItemClickListener);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (SubCatFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement HoofdCatFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private ListView.OnItemClickListener lstSubcatItemClickListener = new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
//mListener.showSubCatActivity(pos+1);
}
};
}
Use FragmentActivity.
public class SubCatActivity extends FragmentActivity{
....
}
FragmentActivity
Replace or add the fragment inside onPostCreate, not on onCreate.
Related
I need Add SearchBar in ActionBar handle with more Fragments like whatsApp
when Search in Tab chats get data and when Search in Tab Status get another data
How do This?This is My Code there is 3 tabs i need every tab there is SearchView
This Activity which there is on Fragments
public class ActivityForIncludeFragments extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_for_include_fragments);
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
CategoryAdapter adapter = new CategoryAdapter(this,getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
invalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem menuItemAddData = menu.findItem(R.id.add_data);
MenuItem menuItemActionSearch = menu.findItem(R.id.action_search);
menuItemAddData.setVisible(false);
menuItemActionSearch.setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.add_stocking_warehouse:
Intent intent = new Intent(ActivityForIncludeFragments.this,StockingWarehouse.class);
startActivity(intent);
break;
case R.id.add_reportes:
Intent intentReport = new Intent(ActivityForIncludeFragments.this,TableDaliyMovmentes.class);
startActivity(intentReport);
break;
}
return super.onOptionsItemSelected(item);
}
}
and This Fragment there is the data
public class AddPremissionFragment extends Fragment implements
LoaderManager.LoaderCallbacks<ArrayList<ItemsStore>>
,SearchView.OnQueryTextListener {
public AddPremissionFragment() {
// Required empty public constructor
}
public static final String ID_PERMISSION = "id";
public static final String NAME_PERMISION = "namePErmission";
public static final String NOTES_PERMISSION = "notes";
public static final String DIALOG_PERMISSION = "dialogPermission";
FloatingActionButton fab_add_permission;
ListView mListView;
public static AdapterAddPermission adapterAddPermission;
TaskDbHelper dbHelper;
ArrayList<ItemsStore> itemsPermissions = new ArrayList<ItemsStore>();
private ProgressBar progressBarPermission;
//Identifier for the category dataloader;
public static final int PERMISSION_LOADER = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_add_premission, container, false);
TextView namePremission = (TextView)view.findViewById(R.id.ETTypeStore);
dbHelper = new TaskDbHelper(getActivity());
mListView = (ListView) view.findViewById(R.id.listViewAddPermission);
progressBarPermission =(ProgressBar)view.findViewById(R.id.progressBarPermission);
adapterAddPermission = new AdapterAddPermission(getContext(), itemsPermissions);
View emptyView = view.findViewById(R.id.empty_view_permission);
mListView.setEmptyView(emptyView);
mListView.setAdapter(adapterAddPermission);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getContext(), "Click :"+ position, Toast.LENGTH_SHORT).show();
ItemsStore itemSPermision = itemsPermissions.get(position);
Bundle bundle = new Bundle();
bundle.putInt(ID_PERMISSION, itemSPermision.getId());
bundle.putString(NAME_PERMISION, itemSPermision.getNamePermission());
bundle.putString(NOTES_PERMISSION, itemSPermision.getNotes());
// startActivity(intent);
// long id = cursor.getLong(cursor.getColumnIndex(TaskContract.TaskEntry._ID));
EditPermissionFragment f = new EditPermissionFragment();
f.setArguments(bundle);
f.show(getFragmentManager(),DIALOG_PERMISSION);}});
// namePremission.setText("Name Permission");
fab_add_permission = (FloatingActionButton)view.findViewById(R.id.fab_add_permission);
fab_add_permission.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new EditPermissionFragment().show(getFragmentManager(),DIALOG_PERMISSION);
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Kick off the loader
getActivity().getSupportLoaderManager().initLoader(PERMISSION_LOADER, null, this);
}
#Override
public Loader<ArrayList<ItemsStore>> onCreateLoader(int id, Bundle args) {
return new LoaderPErmission(getContext().getApplicationContext(),itemsPermissions,dbHelper);
}
#Override
public void onLoadFinished(Loader<ArrayList<ItemsStore>> loader, ArrayList<ItemsStore> data) {
progressBarPermission.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
adapterAddPermission.swapData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<ItemsStore>> loader) {
adapterAddPermission.swapData(Collections.<ItemsStore>emptyList());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(this);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
itemsPermissions = dbHelper.getAllItemsPermissionBySearch(newText);
if (itemsPermissions !=null){
adapterAddPermission.setFilter(itemsPermissions);
// getSupportLoaderManager().restartLoader(Daily_LOADER,null,this);
}
return false;
}
}
Please check which fragment is visible using this
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment != null && fragment.isVisible()) {
if (fragment instanceof ChatFragment) {
....
}
else { }
}
I am just creating a simple List-fragment but my application won't run on AVD .Can't figure out error.
Here is my MainActivity.java
package in.blogspot.food_n_moreblog.recipes;
public class MainActivity extends Activity implements catagorylistfrag.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void itemClicked(long id){
catagorydetailfragment detailfragment=new catagorydetailfragment();
FragmentTransaction ft=getFragmentManager().beginTransaction();
detailfragment.setWorkout(id);
ft.replace(R.id.fragment_container,detailfragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
DetailFragment(java code)
package in.blogspot.food_n_moreblog.recipes;
public class catagorydetailfragment extends Fragment {
private long workoutID;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
if (savedInstanceState!=null)
{
workoutID=savedInstanceState.getLong("workoutID");
}
return inflater.inflate(R.layout.catagorydetails,container,false);
}
#Override
public void onStart()
{
super.onStart();
View view=getView();
if(view!=null){
TextView title=(TextView)view.findViewById(R.id.titleText);
CatagoryValues value=CatagoryValues.catagories[(int)workoutID];
title.setText(value.getName());
TextView des=(TextView)view.findViewById(R.id.detailText);
des.setText(value.getDescription());
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putLong("workoutID",workoutID);
}
public void setWorkout(long id){
this.workoutID=id;
}
}
List item Fragment java code
package in.blogspot.food_n_moreblog.recipes;
public class catagorylistfrag extends ListFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
public static catagorylistfrag newInstance(String param1, String param2) {
catagorylistfrag fragment = new catagorylistfrag();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public catagorylistfrag() {
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
/*if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}*/
String[] names=new String[CatagoryValues.catagories.length];
for(int i=0;i<names.length;i++){
names[i]=CatagoryValues.catagories[i].getName();
}
// TODO: Change Adapter to display your content
ArrayAdapter<String> adapter=new ArrayAdapter<String>(inflater.getContext(),android.R.layout.simple_expandable_list_item_2,names);
setListAdapter(adapter);
return super.onCreateView(inflater,container,savedInstanceState);
}
#Override
public void onAttach(Context context) {
/* super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
*/super.onAttach(context);
Activity a;
if (context instanceof Activity){
a=(Activity) context;
this.mListener=(OnFragmentInteractionListener)a;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.itemClicked(id);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
// public void onFragmentInteraction(String id);
void itemClicked(long id);
}
}
Try this array adapter in your list item Fragment java code:
ArrayAdapter<String> adapter=new ArrayAdapter<String>(inflater.getContext(),android.R.layout.android.R.layout.simple_list_item_1,names);
My fragment's code looks like this:
public class AllIssuesFragment extends Fragment {
#Bind(R.id.list_all_issues) ListView mListAllIssues;
IssuesGetter ai;
ArrayAdapter<IssuesResponse.Issue> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_issues, container, false);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
setRetainInstance(true);
SharedPreferences user_data = this.getActivity().getSharedPreferences("user_data", Context.MODE_PRIVATE);
UserManager.getInstance().setUsername(user_data.getString("username", null));
UserManager.getInstance().setPassword(user_data.getString("password", null));
if(UserManager.getInstance().getUsername() == null || UserManager.getInstance().getPassword() == null) {
Intent intent = new Intent(getActivity(), ChangeUserActivity.class);
startActivity(intent);
}
else {
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1);
if(savedInstanceState == null) {
getIssues(Constants.URI + Constants.ISSUES + Constants.OFFSET + 0);
}
mListAllIssues.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = firstVisible + visibleCount >= totalCount;
if (loadMore && ai.getStatus() == AsyncTask.Status.FINISHED) {
getIssues(Constants.URI + Constants.ISSUES + Constants.OFFSET + totalCount);
mListAllIssues.setSelection(totalCount);
}
}
});
}
}
private void getIssues(String url) {
ai = new IssuesGetter(new AsyncCallback<IssuesResponse>() {
#Override
public void onSuccess(IssuesResponse response) {
int index = mListAllIssues.getFirstVisiblePosition();
View v = mListAllIssues.getChildAt(0);
int top = (v == null)? 0 : v.getTop();
adapter.addAll(response.getIssues());
adapter.notifyDataSetChanged();
mListAllIssues.setAdapter(adapter);
mListAllIssues.setSelectionFromTop(index, top);
}
#Override
public void onError() {
Intent intent = new Intent(getActivity(), ChangeUserActivity.class);
startActivity(intent);
}
});
ai.execute(url);
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Bind(R.id.viewpager) ViewPager viewPager;
#Bind(R.id.tabs) PagerSlidingTabStrip tabStrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
viewPager.setAdapter(new MainActivityPagerAdapter(getSupportFragmentManager()));
tabStrip.setViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_change_user) {
Intent intent = new Intent(this, ChangeUserActivity.class);
this.startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
I've tried to use setRetainInstance(true) and check if the savedInstanceState equals null, but it didn't solve my problem. I am stuck :(
My Asynctask returns result using call back.
I see the problem here:
public void onCreate() {
//..
viewPager.setAdapter(new MainActivityPagerAdapter(getSupportFragmentManager()));
tabStrip.setViewPager(viewPager);
}
This method is called each time activity is recreated. And what it does is creates new adapter which creates brand new fragments. And that is a problem. Because your activity doesn't control creation of fragments. That is neccessary in order to retain fragments.
I suggest you to save state of fragment in onSaveInstanceState() callback and restore it in onCreateView(). Note that you don't need to save state of UI elements just variables of fragment class. UI elements save their state automatically if they have unique id.
EDIT:
My suggestion:
public class AllIssuesFragment extends Fragment {
private List<String> issues;
// ..
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ..
if (null != savedInstanceState) {
issues = savedInstanceState.getStringArray("issues");
} else {
issues = new List<>();
}
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, issues);
// ..
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArray("issues", issues);
}
private void getIssues(String url) {
// ..
ai = new IssuesGetter(new AsyncCallback<IssuesResponse>() {
#Override
public void onSuccess(IssuesResponse response) {
// ..
//adapter.addAll(response.getIssues());
issues.addAll(response.getIssues());
adapter.notifyDataSetChanged();
// ..
}
};
// ..
}
}
I am trying to populate data into autoCompleteTextView using ArrayAdapter whenever I run the application it tells me "Unfortunately the application has stopped". This part is an a gosh for me "adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, words);
edit.setAdapter(adapter);" What have i done wrong? Please help
public class MainActivity extends ActionBarActivity implements TextWatcher
{
private static final String DB_NAME = "mydata.sqlite3";
ArrayAdapter<String> adapter;
private SQLiteDatabase database;
private ArrayList<String> words;
private AutoCompleteTextView edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
edit = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
setWordList();
}
private void setWordList()
{
words = new ArrayList<String>();
Cursor friendCursor = database.rawQuery("SELECT * FROM WordTableList", null);
friendCursor.moveToFirst();
if(!friendCursor.isAfterLast())
{
do
{
String myWord = friendCursor.getString(1);
words.add(myWord);
} while (friendCursor.moveToNext());
}
friendCursor.close();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, words);
edit.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
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 {
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 onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
I am using the following library for my sliding menu (https://github.com/bk138/LibSlideMenu) in my app.
In my app the sliding menu works. I can slide from right to left and the menu will appear. But the problem is that when I am in the menu I can't slide back to the fragment were I came from.
The only way to get back is using back button. Also when you are in the menu I don't have the padding on the right where you see the previous fragment on the background.
I am searching for it like days. I have searched the example for the problem but couldn't find the essential thing that i am forgetting.
My main activity:
public class MainActivity extends SlidingFragmentActivity {
private Fragment rFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setBehindContentView(R.layout.menu_frame);
if (savedInstanceState != null)
rFrag = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
if (rFrag == null)
rFrag = new RecentGridFragment();
FragmentTransaction fragment = getSupportFragmentManager().beginTransaction();
fragment.replace(R.id.content_frame, rFrag);
MenuFragment mFrag = new MenuFragment();
fragment.replace(R.id.menu_frame, mFrag);
fragment.commit();
//Sliding menu
SlidingMenu sMenu = new SlidingMenu(this);
sMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sMenu.setShadowWidthRes(R.dimen.shadow_width);
sMenu.setShadowDrawable(R.drawable.shadow);
sMenu.setBehindScrollScale(0.25f);
sMenu.setFadeDegree(0.25f);
sMenu.setSlidingEnabled(true);
sMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "mContent", rFrag);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
}
return super.onOptionsItemSelected(item);
}
public void switchContent(final Fragment inputFrag) {
rFrag = inputFrag;
FragmentTransaction fragment = getSupportFragmentManager().beginTransaction();
fragment.replace(R.id.content_frame, inputFrag);
fragment.commit();
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
getSlidingMenu().showContent();
}
}, 50);
}}
Menu:
public class MenuFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] birds = getResources().getStringArray(R.array.birds);
ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, birds);
setListAdapter(colorAdapter);
}}
The mainfragment that has the content
public class RecentGridFragment extends Fragment {
private int mImgRes;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mImgRes = R.drawable.peacock;
GridView gv = (GridView) inflater.inflate(R.layout.list_grid, null);
gv.setBackgroundResource(android.R.color.black);
gv.setAdapter(new GridAdapter());
return gv;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private class GridAdapter extends BaseAdapter {
#Override
public int getCount() {
return 30;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.grid_item, null);
}
ImageView img = (ImageView) convertView.findViewById(R.id.grid_item_img);
img.setImageResource(mImgRes);
return convertView;
}
}}
I have found my mistake:
I need to get the slidingactivity instead of making a new one.
SlidingMenu sMenu = this.getSlidingMenu();