there are to many threads talking about this but i tried everything and doens't seem to work. My Problem is kinda simple i have a viewpager with 5 fragments pages.
Each of this fragment has the same layout only 1 edit text, and the issue is if i write something on the editext onswipe to next or the previous page i would like to reset that edittext.
For example:
PAGE1: editext=2929 ---(swipe)--- PAGE2: edittext = 0 ----(swipe)--- PAGE1:edittext = 0
But it always shows the 2929.
I to do this for my app, im trying to this on teste program.
this is my Adpater
public class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
int PAGE_COUNT;
int total;
Fragment frag;
FragmentManager fmm;
/** Constructor of the class */
public MyFragmentPagerAdapter(FragmentManager fm, int x, int total) {
super(fm);
fmm = fm;
total = 0;
PAGE_COUNT = x;
}
/** This method will be invoked when a page is requested to create */
#Override
public Fragment getItem(int arg0) {
final FragmentTab11 myFragment = new FragmentTab11();
Bundle data = new Bundle();
data.putInt("current_page", arg0 + 1);
myFragment.setArguments(data);
return myFragment;
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
this my fragment
public class FragmentTab11 extends SherlockFragment {
int mCurrentPage;
TextView tv;
EditText edt;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Getting the arguments to the Bundle object */
Bundle data = getArguments();
/** Getting integer data of the key current_page from the bundle */
mCurrentPage = (data != null) ? data.getInt("current_page", 0) : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_one1, container, false);
tv = (TextView) v.findViewById(R.id.textView1);
tv.setText("You are viewing the page #" + mCurrentPage
+ " of Frag1\n\n" + "Swipe Horizontally left / right");
btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
update();
}
});
edt = (EditText) v.findViewById(R.id.editText1);
return v;
}
public void update() {
Log.w("text", mCurrentPage+": " + edt.getText().toString());
edt.setText("");
}
#Override
public void onDetach() {
edt.post(new Runnable() {
#Override
public void run() {
edt.setText("");
Log.w("DETACH", "CurrentPage " + mCurrentPage);
}
});
super.onDetach();
}
And what i like to do its the same of the button listener, reset the edittext but instead of clicking it, it would be on swipe gesture.
Thank you,
Gonçalo Moura
EDIT:
xml from fragment_one1
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="1" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:ems="10" >
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" /></LinearLayout>
view pager:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" /></LinearLayout>
I tried remove the fragment from FragmentManger,
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
also, tv.setOffscreenPageLimit(limit);, tried FragmentStatePagerAdapter and FragmentPagerAdapter, i have state because it destroys the fragment, using events onDetach(), onDestroy() etc etc, if you saw the code of the fragment you can see my method onDetach(), notifydatasetchanged, setting new adapter.
well i figured it out.
Well as we "all" know viewpager creates 3 pages, and this pages will be set at NOT VISIBLE and VISIBLE. I googled around and found this:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Log.w("Visible1", "CurrentPage " + mCurrentPage);
} else {
Log.w("NOTVISIBLE1", "CurrentPage " + mCurrentPage);
if (edt != null) {
edt.setText("");
}
}
}
Well when i swipe and swipe back my values will be reseted, the "if" is because the view maybe its not created yet, this method is called before the onCreate() method. But it works, i don't know if you guys agree or have a better solution for this. I hope it will help someone.
Cheers
Related
I have an activity that contains one ViewPager (nothing else). The fragments I use are extremely simple. They consist of a flat background with two buttons (back and forward).
When the ViewPager scrolls with user input it works smoothly. However, when I program the buttons to use setCurrentItem to the next page the animation is really choppy.
The "choppyness" is only the first time the animation executes. After that, if I go back and forth using the buttons the animation is smooth.
Because of this behavior, I imagine that it has something to do with the way that PageViewer anticipates user behavior. If anyone can shed some light on this matter that would be of great help. Thanks!
I read about similar issues with PageViewer animations being choppy (all of them more than 3 years old). I tried their suggestions and could not get it to work; so I decided to create a new question.
Here is the code I am using:
MainActivity.java
public class MainActivity extends Activity implements MyFragment.Listener {
private ViewPager _pager;
private PagerAdapter _adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
_pager = (ViewPager)findViewById(R.id.pager);
_adapter = new MyAdapter(this, getFragmentManager());
_pager.setAdapter(_adapter);
}
public void next() {
if(_pager.getCurrentItem() + 1 >= _adapter.getCount()) return;
_pager.setCurrentItem(_pager.getCurrentItem() + 1, true);
}
public void previous() {
if(_pager.getCurrentItem() - 1 < 0) return;
_pager.setCurrentItem(_pager.getCurrentItem() - 1, true);
}
}
MyAdapter.java
public class MyAdapter extends FragmentStatePagerAdapter {
private static final int PAGES = 3;
private ArrayList<Fragment> _slides;
public MyAdapter(MainActivity l, FragmentManager fm) {
super(fm);
_slides = new ArrayList<>();
for(int i = 0; i < PAGES; i++) {
MyFragment f = new MyFragment();
f.addListener(l);
_slides.add(f);
}
}
public Fragment getItem(int position) { return _slides.get(position); }
public int getCount() { return _slides.size(); }
}
MyFragment.java
public class MyFragment extends Fragment {
public interface Listener {
void next();
void previous();
}
private ArrayList<Listener> ls = new ArrayList<>();
public void addListener(Listener l) { ls.add(l); }
protected void next() { for(Listener l : ls) l.next(); }
protected void previous() { for(Listener l : ls) l.previous(); }
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
view.setBackgroundColor(Color.argb(255, (int)(Math.random() * 255), (int)(Math.random() * 255), (int)(Math.random() * 255)));
Button bNext = (Button)view.findViewById(R.id.button_next);
bNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
next();
}
});
Button bPrevious = (Button)view.findViewById(R.id.button_previous);
bPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
previous();
}
});
return view;
}
}
main_activity.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
my_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:id="#+id/button_previous"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="previous" />
<Button
android:id="#+id/button_next"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="next" />
</LinearLayout>
Create a custom view pager class by extending ViewPager
Override the smoothScrollTo(...) method
void smoothScrollTo(int x, int y, int v) {
super.smoothScrollTo(x, y, 1);
}
The default value used is 0. When you pass 1, scrolling is smooth.
I am new to Android and am trying a sample application for showing ViewPagers in a Master-Detail Flow using custom PagerAdapters and FragmentStatePagerAdapters. My application has a list of dummy items managed by a SQLiteDatabase which contain a title String, a description String, a Boolean like status, and a list of images (I plan to implement them as downloading from String urls but presently I'm just trying with a single image resource). I am having two problems in the Detail View.
My intention is to use a ViewPager with a FragmentStatePagerAdapter to show the detail view, which consists of a ViewPager with a custom PagerAdapter for showing the list of images, TextView for title and description, a ToggleButton for the like status and a delete button for deleting items from the list.
Issues:
The ViewPager with the custom PagerAdapter does not display the image. It occupies the expected space and swipes performed on it also behave as expected. Only the image is not visible.
[RESOLVED] On using the delete button, I am able to delete the item from the database, and also update the Master View accordingly, but I am not able to update the Detail View, and the app crashes.
Here is my code:
Code that calls ItemDetailActivity.java
#Override
public void onClick(View v) {
Intent detailIntent = new Intent(getContext(), ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_LIST_POSITION, holder.position);
getContext().startActivity(detailIntent);
}
ItemDetailActivity.java
public class ItemDetailActivity extends FragmentActivity {
static ItemDetailPagerAdapter idpa;
static ViewPager detailPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
idpa = new ItemDetailPagerAdapter(getSupportFragmentManager());
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
detailPager = (ViewPager) findViewById(R.id.item_detail_container);
detailPager.setAdapter(idpa);
detailPager.setCurrentItem(getIntent().getIntExtra(ItemDetailFragment.ARG_LIST_POSITION, 0));
}
}
activity_item_detail.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.trial.piclist.ItemDetailActivity"
tools:ignore="MergeRootFrame" />
ItemDetailFragment.java
public class ItemDetailFragment extends Fragment {
public static final String ARG_ITEM_ID = "item_id";
public static final String ARG_LIST_POSITION = "list_index";
public static final String ARG_TWO_PANE = "is_two_pane";
int position = -1;
long id = -1;
boolean twoPane = false;
ViewPager pager;
private PicItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
twoPane = getArguments().getBoolean(ARG_TWO_PANE, false);
position = getArguments().getInt(ARG_LIST_POSITION, -1);
id = getArguments().getLong(ARG_ITEM_ID, -1);
if (id == -1)
id = ItemListFragment.getIdByPosition(position);
setmItem(id);
}
public void setmItem(long id) {
if (id >= 0) {
try {
ItemListActivity.lds.open();
mItem = ItemListActivity.lds.getById(id);
ItemListActivity.lds.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
if (mItem != null) {
List<String> pics = new ArrayList<String>();
pics.add("1");
pics.add("2");
pics.add("3");
pics.add("4");
pics.add("5");
mItem.setPics(pics);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
DetailViewHolder holder = new DetailViewHolder();
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),
inflater, position);
pager.setAdapter(adapter);
holder.position = getArguments().getInt(ARG_LIST_POSITION);
holder.ttv = (TextView) rootView.findViewById(R.id.item_title);
holder.dtv = (TextView) rootView.findViewById(R.id.item_detail);
holder.likeButton = (ToggleButton) rootView
.findViewById(R.id.item_like);
holder.deleteButton = (Button) rootView.findViewById(R.id.item_delete);
rootView.setTag(holder);
if (mItem != null) {
holder.ttv.setText(mItem.getTitle());
holder.dtv.setText(mItem.getDescription());
holder.likeButton.setChecked(mItem.getIsLiked());
holder.likeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.toggleLike(mItem.getId());
mItem.toggleIsLiked();
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.toggleLiked(position);
}
});
holder.deleteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ItemListActivity.lds.open();
ItemListActivity.lds.removeItem(mItem.getId());
ItemListActivity.lds.close();
ItemListFragment.listDisplayHelper.remove(position);
ItemListActivity.idpa.notifyDataSetChanged();
// What do I do so that the FragmentStatePagerAdapter is
// updated and the viewpager shows the next item.
}
});
}
return rootView;
}
static private class DetailViewHolder {
TextView ttv;
TextView dtv;
ToggleButton likeButton;
Button deleteButton;
int position;
}
}
fragment_item_detail.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="com.trial.piclist.ItemDetailFragment" >
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="200dip">
</android.support.v4.view.ViewPager>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/item_title"
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:textIsSelectable="true" />
<Space
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="#layout/controls_layout" />
</TableRow>
<ScrollView
android:id="#+id/descScrollView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/item_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
</ScrollView>
</LinearLayout>
controls_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ToggleButton
android:id="#+id/item_like"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_gravity="right"
android:background="#android:drawable/btn_star"
android:gravity="center"
android:text="#string/like_list_item"
android:textOff="#string/empty_text"
android:textOn="#string/empty_text" />
<Button
android:id="#+id/item_delete"
style="?android:attr/buttonStyleSmall"
android:layout_width="30dip"
android:layout_height="30dip"
android:background="#android:drawable/ic_menu_delete"
android:text="#string/empty_text" />
</LinearLayout>
Custom PagerAdapter
ImagePagerAdapter.java
public class ImagePagerAdapter extends PagerAdapter {
LayoutInflater inflater;
List<View> layouts = new ArrayList<>(5);
// Constructors.
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (layouts.get(position) != null) {
return layouts.get(position);
}
View layout = inflater.inflate(R.layout.detail_image,
((ViewPager) container), true);
try {
ImageView loadSpace = (ImageView) layout
.findViewById(R.id.detail_image_view);
loadSpace.setBackgroundColor(0x000000);
loadSpace.setImageResource(R.drawable.light_grey_background);
loadSpace.setAdjustViewBounds(true);
} catch (Exception e) {
System.out.println(e.getMessage());
}
layout.setTag(images.get(position));
layouts.set(position, layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (((View) object).findViewById((view.getId())) != null);
}
}
FragmentPagerAdapter
ItemDetailPagerAdapter.java
public class ItemDetailPagerAdapter extends FragmentStatePagerAdapter {
public ItemDetailPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ItemDetailFragment();
Bundle args = new Bundle();
args.putLong(ItemDetailFragment.ARG_ITEM_ID, ItemListFragment.getIdByPosition(position));
args.putInt(ItemDetailFragment.ARG_LIST_POSITION, position);
args.putBoolean(ItemDetailFragment.ARG_TWO_PANE, ItemListActivity.mTwoPane);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
openDatabase();
int c = database.getCount();
closeDatabase();
return c;
}
#Override
public int getItemPosition(Object object) {
long mId = ((ItemDetailFragment) object).getmId();
int pos = POSITION_NONE;
openDatabase();
if (database.contains(mId)) {
pos = database.getPositionById(mId);
}
closeDatabase();
return pos;
}
}
Any help is much appreciated. Thanks :)
In your ItemDetailFragment, remove the viewpager from the holder, it should be directly into the returned view, something like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
pager = (ViewPager) rootView.findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(mItem, getActivity(),inflater, position);
pager.setAdapter(adapter);
return rootView;
}
and the ViewHolder pattern should be applied inside your PagerAdapter.
In ImagePagerAdapter.java, correct the isViewFromObject method -
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (View) object);
}
This will correct the issue of the ImageView.
In ItemDetailPagerAdapter.java, override the getItemPosition method -
#Override
public int getItemPosition(Object object) {
int ret = POSITION_NONE;
long id = ((ItemDetailFragment) object).getId();
openDatabase();
if (databaseContains(id)) {
ret = positionInDatabase(id);
}
closeDatabase();
return ret;
}
On deleting call the FragmentStatePagerAdapter.NotifyDataSetChanged() method. This will make the Adapter update itself on deleting.
Although, the FragmentStatePagerAdapter uses a list of Fragments and of stored states to implement the adapter. That is also causing trouble. To remove that, implement your own list of Fragments.
I develope currently a small sample app with fragments and a viewPager. The viewPager shows 3 pages. In each page i instantiate a fragment of the same type. The fragment contains a textView and a button. On button click I want to replace the current fragment with another one. Now my problem is, no matter which button I press only the fragment of page 1 gets replaced. I dont know what I have to do in my pageAdapter class but I guess it has to do with using the same fragment and layout. I think I have to make sure, that my pageAdapter updates the correct page, but how do I achieve that?
For a better understanding why I want to achieve that, that I receive a json string within 3 node of type menu and I want to use each of them as a page in my viewPager.
Can someone show me a short and easy example for such a behavior? I think its a basic approach, so it cant be so difficult.
--------Edit---------
Here is the code:
public class FragmentPagerSupport extends FragmentActivity {
static final int NUM_ITEMS = 4;
MyAdapter mAdapter;
ViewPager mPager;
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}
public MyAdapter getmAdapter() {
return mAdapter;
}
public ViewPager getmPager() {
return mPager;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getFragmentManager(), this);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setOffscreenPageLimit(NUM_ITEMS + 2);
mPager.setAdapter(mAdapter);
Button button = (Button) findViewById(R.id.goto_first);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.goto_last);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(NUM_ITEMS - 1);
}
});
}
}
MyAdapter:
public MyAdapter(FragmentManager fm, FragmentPagerSupport fragmentPagerSupport) {
super(fm);
this.fragmentPagerSupport = fragmentPagerSupport;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
Fragment newInstance = null;
switch (position) {
case 0:
newInstance = frag1.newInstance(position);
break;
case 1:
newInstance = frag1.newInstance(position);
break;
case 2:
newInstance = frag2.newInstance(position);
break;
case 3:
newInstance = frag2.newInstance(position);
break;
}
return newInstance;
}
Frag1 & Frag2 & ListItemFrag:
public static class frag1 extends ListFragment {
int mNum;
static frag1 newInstance(int num) {
frag1 f = new frag1();
Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class frag2 extends ListFragment {
int mNum;
static frag2 newInstance(int num) {
frag2 f = new frag2();
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class ListItemFragment extends Fragment {
String itemName;
static ListItemFragment newInstance(String itemName) {
ListItemFragment i = new ListItemFragment();
Bundle args = new Bundle();
args.putString("text", itemName);
i.setArguments(args);
return i;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
itemName = getArguments() != null ? getArguments().getString("text") : "NULL";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_item, container, false);
View tv = v.findViewById(R.id.textView1);
((TextView) tv).setText("Cheese: " + itemName + " selected!");
return v;
}
}
Pager Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center" android:measureWithLargestChild="true"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0">
<Button
android:id="#+id/goto_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first" />
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="last">
</Button>
</LinearLayout>
Frag1 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
Frag2 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test2">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root2" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
ListItemFrag Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="230dp"
android:background="#AA33EE"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Hi I was facing same kind of issue. I fixed the issue by using
getChildFragmentManager().beginTransaction()
instead of
getActivity().getSupportFragmentManager().beginTransaction()
As in this case we are trying to make transaction from within a fragment (one out of the list of fragments which are attached to the ViewPager, thus the Activity holding the ViewPager) so we have to use getChildFragmentManager() here for desired results.
NOTE: I am using android support v4 library and thus corresponding FragmentManager.
In my project i am using actionbar with swipeable threefragments(tabs with viewpager), i am trying to replace one of the fragment with fourth fragment, but iam not able to get it..
**Below is my code**
public class GetRideFragment extends Fragment implements ICustomDateTimeListener, SelectedLocationListener{
public GetRideFragment() {
}
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_getride, container, false);
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fromac.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* Intent newintent = new Intent(getActivity(), AutoSearchActivity.class);
startActivity(newintent);
getActivity().overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );*/
PlaceSearchFragment fh = new PlaceSearchFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragcontainer, fh);
ft.addToBackStack("fh");
ft.commit();
}
});
Below is my layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragcontainer">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/fragcontainer"
>
<TextView
android:id="#+id/ridetitile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get a Ride"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
android:textColor="#33b5e5"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:background="#drawable/gray_btn_disabled_normal" >
...............
...........
My adpater
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new GetRideFragment();
case 1:
// Games fragment activity
return new PostRideFragment();
case 2:
// Movies fragment activity
return new SearchRidesFragment();
}
return null;
}
#Override
public int getItemPosition(Object object){
return PagerAdapter.POSITION_NONE;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
nNot sure where i am going wrong.Any help is appreciated.
I had the same problem. I found the solution after a lot of searches. I would see 2 problems in your code: (sorry for my bad english)
1) to change an item inside the adapter (connected to your viewpager) for a given position, you have to change the items returned by the method public Fragment getItem(int index) and call the method notifyDataSetChanged() to notify to the adapter that the content is changed.
2) the implementation of the FragmentStatePagerAdapter contains a cache based on the position and it doesn't change even if you call the notifyDataSetChanged() and you return the PagerAdapter.POSITION_NONE (there is an issue reported here: https://code.google.com/p/android/issues/detail?id=37990)
what I would suggest you is:
use a FragmentPagerAdapter, implement properly the methods getItem(int index) (with the correct item at the given position), getItemPosition(Object object), and getItemId(int position)
if you want to use a FragmentStatePagerAdapter, consider the implementation suggested in the issue I liked above (NewFragmentStatePagerAdapter).
I hope it helps!
I try to start a tab, which can be swiped. It works fine! But if I try to implement Google Maps, then it works unit I switch the tab and go to the map back. I get these kind of Error:
E/AndroidRuntime(25324): FATAL EXCEPTION: main
E/AndroidRuntime(25324): android.view.InflateException: Binary XML file line #21: Error inflating class fragment
I searched many times in google and couldn't find a solution.
This is the MainActivity class Code:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
GoogleMapOptions nMap;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
Fragment f1 = new LayersDemoActivity2();
return f1;
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0: return "Timeline";
case 1: return "Chat";
case 2: return "Fh";
case 3: return "Mehr";
default: return "Section " + (position + 1);
}
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Tab 1 calls this Fragment
public class LayersDemoActivity2 extends Fragment implements OnItemSelectedListener {
private GoogleMap mMap;
private CheckBox mTrafficCheckbox;
private CheckBox mMyLocationCheckbox;
//neu hinzugekommen
private LocationClient locationclient;
private String TAG = this.getClass().getSimpleName();
//neu hinzugekommen
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.layers_demo, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.traffic)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateTraffic();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.my_location)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateMyLocation();
}
});
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.button1)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkReady()) {
return;
}
try{
LatLng hier = new LatLng(mMap.getMyLocation().getLatitude(), mMap.getMyLocation().getLongitude());
Marker setzen = mMap.addMarker(new MarkerOptions().position(hier).title("Here I am!"));
}catch(Exception e){
}
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
Spinner spinner = (Spinner) getView().findViewById(R.id.layers_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getView().getContext(), R.array.layers_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
mTrafficCheckbox = (CheckBox) getView().findViewById(R.id.traffic);
mMyLocationCheckbox = (CheckBox) getView().findViewById(R.id.my_location);
setUpMapIfNeeded();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
if (mMap != null) {
updateTraffic();
updateMyLocation();
}
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
private boolean checkReady() {
if (mMap == null) {
//getView().Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void updateTraffic() {
if (!checkReady()) {
return;
}
mMap.setTrafficEnabled(mTrafficCheckbox.isChecked());
}
private void updateMyLocation() {
if (!checkReady()) {
return;
}
mMap.setMyLocationEnabled(mMyLocationCheckbox.isChecked());
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setLayer((String) parent.getItemAtPosition(position));
}
private void setLayer(String layerName) {
if (!checkReady()) {
return;
}
if (layerName.equals(getString(R.string.normal))) {
mMap.setMapType(MAP_TYPE_NORMAL);
} else if (layerName.equals(getString(R.string.hybrid))) {
mMap.setMapType(MAP_TYPE_HYBRID);
} else if (layerName.equals(getString(R.string.satellite))) {
mMap.setMapType(MAP_TYPE_SATELLITE);
} else if (layerName.equals(getString(R.string.terrain))) {
mMap.setMapType(MAP_TYPE_TERRAIN);
} else {
Log.i("LDA", "Error setting layer with name " + layerName);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
last but not least, this is layers_demo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<!-- A set of test checkboxes. -->
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#id/map"
android:background="#D000"
android:orientation="vertical"
android:padding="6dp" >
<Spinner
android:id="#+id/layers_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/traffic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onTrafficToggled"
android:text="#string/traffic" />
<CheckBox
android:id="#+id/my_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onMyLocationToggled"
android:text="#string/my_location" />
</LinearLayout>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:onClick="tagOnMyLocation"
android:text="#string/tag_me" />
and the activity_main.xml layout
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I guess it has something to do with fragment, but I dont know how and I dont know why. Please help. :(
Just paste this method after oncreatview method
#Override
public void onDestroyView() {
Fragment f = (Fragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getFragmentManager().beginTransaction().remove(f).commit();
}
super.onDestroyView();
}