How can I use different views in the viewpages? I cant figure it out.
For example a view with listbox and a view with buttons.
This is my code:
How can I use different views in the viewpages? I cant figure it out.
For example a view with listbox and a view with buttons.
This is my code:
package com.stylingandroid.viewpager;
import com.viewpagerindicator.TitlePageIndicator;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class ViewPagerActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
pager.setAdapter(adapter);
indicator.setViewPager(pager);
}
}
And here the adapter:
package com.stylingandroid.viewpager;
import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;
import com.viewpagerindicator.TitleProvider;
public class ViewPagerAdapter extends PagerAdapter
implements TitleProvider
{
private static String[] titles = new String[]
{
"Page 1",
"Page 2",
"Page 3"
};
private final Context context;
public ViewPagerAdapter( Context context )
{
this.context = context;
}
#Override
public String getTitle( int position )
{
return titles[ position ];
}
#Override
public int getCount()
{
return titles.length;
}
#Override
public Object instantiateItem( View pager, int position )
{
TextView v = new TextView( context );
v.setText(titles[position]);
((ViewPager)pager).addView(v,0);
return v;
}
#Override
public void destroyItem( View pager, int position, Object view )
{
((ViewPager)pager).removeView( (TextView)view );
}
#Override
public boolean isViewFromObject( View view, Object object )
{
return view.equals( object );
}
#Override
public void finishUpdate( View view ) {}
#Override
public void restoreState( Parcelable p, ClassLoader c ) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate( View view ) {}
}
You need to modify the instantiateItem() method in the PagerAdapter and construct each view dynamically rather than simply adding a TextView each time. You could, for example, inflate a different layout for each position:
#Override
public Object instantiateItem( View pager, int position )
{
LayoutInflator inflator = LayoutInflator.from( context );
View v = null;
switch( position )
{
case 0:
v = inflator.inflate( R.layout.layout1, (ViewPager)pager, false );
break;
case 1:
v = inflator.inflate( R.layout.layout2, (ViewPager)pager, false );
break;
.
.
.
}
v.setText(titles[position]);
((ViewPager)pager).addView(v,0);
return v;
}
You have the code already but I wanted to point out that this needs to be in there if you are going to inflate.
#Override
public boolean isViewFromObject( View view, Object object )
{
return view.equals( object );
}
Related
I have a custom pager adapter (PagerIot) that I have successfully implemented using a fragment as shown below
public class SensorIconFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_listview, container, false);
ButterKnife.bind(this, view);
pagerIot = (PagerIot)container;
I would however like to use the pager adapter in a activity but the problem is I need to know how to initialize the pager in an activity. In a fragment its quite simple because fragments have an onCreateViewMethod where a viewGroup is passed in as a parameter so I can simply say pPagerIot = (PagerIot)container;
In Activity however I cannot simply initialize the PagerIOT because onCreate does not pass in a ViewGroup so does anyone know how I can initialize the adapter in an Activity ?
This is my PagerIOT class below
public class PagerIot extends ViewPager
{
public PagerIot(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void allowScrollingToTab(int tab)
{
// Set the limit of the number of pages in the page adapter
ManagementTabFragment.SectionsPagerAdapter adapter = (ManagementTabFragment.SectionsPagerAdapter)getAdapter();
adapter.allowScrollingToTab(tab);
}
}
I will also include the managenment tab referenced in the class above
package com.dtect.devicesensorinsight.home.tabs;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dtect.common.ITabView;
import com.dtect.common.MyFragmentPagerAdapter;
import com.dtect.devicesensorinsight.R;
import com.dtect.devicesensorinsight.events.JumpToManagementTabEvent;
import com.dtect.devicesensorinsight.home.PagerIot;
import com.dtect.devicesensorinsight.home.tabs.management.CostCentreListFragment;
import com.dtect.devicesensorinsight.home.tabs.management.IotTabFragment;
import com.dtect.devicesensorinsight.home.tabs.management.SensorIconFragment;
//import com.dtect.devicesensorinsight.home.tabs.notifications.TenantDetailsFragment;
import com.dtect.devicesensorinsight.home.tabs.management.iot.SensorInformationChildFragment;
import com.dtect.devicesensorinsight.sensors.ItemClickedEvent;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
public class ManagementTabFragment extends Fragment implements ITabView
{
public static final int TAB_USER_LANDINGPAGE = 0;
public static final int TAB_TENANT_SCANQRCODE= 1;
public static final int TAB_TENANT_DETAILS = 2;
public static final int TAB_UOM_SYMBOLS = 3;
public static final int TAB_LOCATIONS = 4;
public static final int TAB_IOT = 5;
#BindView(R.id.managementpager)
PagerIot viewPager;
private SectionsPagerAdapter sectionsPagerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_management_pages, container, false);
ButterKnife.bind(this, view);
sectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(5);
return view;
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
public void onEvent(JumpToManagementTabEvent tab) {
setSelectedPage(tab.tabIndex);
}
private void setSelectedPage(int index)
{
viewPager.setCurrentItem(index);
}
#Override
public MyFragmentPagerAdapter getAdapter() {
return sectionsPagerAdapter;
}
#Override
public ViewPager getViewPager() {
return viewPager;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends MyFragmentPagerAdapter {
private int allowScrollingToTabOffset = 0;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public void allowScrollingToTab(int tab)
{
this.allowScrollingToTabOffset = tab;
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case TAB_USER_LANDINGPAGE:
return new UserLandingPageFragment();
case TAB_UOM_SYMBOLS:
return new SensorIconFragment();
case TAB_LOCATIONS:
return new CostCentreListFragment();
case TAB_IOT:
return new IotTabFragment();
default:
return null;
}
}
#Override
public int getCount() {
return allowScrollingToTabOffset + 1;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
return "" + position;
}
}
}
Why I am getting an error message showing change
getSupportFragmentManager() in view
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
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.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPropertyAnimatorListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.Random;
import activity.rama.navigationtaskbartraining.R;
import activity.rama.navigationtaskbartraining.flycodialog.IOSTaoBaoDialog;
import activity.rama.navigationtaskbartraining.tabbed.Tab1Contact;
import activity.rama.navigationtaskbartraining.tabbed.Tab2Chat;
import activity.rama.navigationtaskbartraining.tabbed.Tab3Online;
import activity.rama.navigationtaskbartraining.tabbed.TabbedActivity;
import butterknife.Bind;
import cn.pedant.SweetAlert.SweetAlertDialog;
import devlight.io.library.ntb.NavigationTabBar;
import static android.content.ContentValues.TAG;
/**
* Created by GIGAMOLE on 28.03.2016.
*/
public class HorizontalCoordinatorNtbAndTabbedActivity extends Activity implements View.OnClickListener {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
private ExpandableListView.OnChildClickListener view2;
private TabbedActivity.SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private FragmentActivity myContext;
private FragmentManager FragManager;
#Bind(R.id.elv)
ExpandableListView mElv;
private Context mContext = this;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horizontal_coordinator_ntb);
initUI();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initUI() {
final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
viewPager.setAdapter(new PagerAdapter() {
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
#Override
public void destroyItem(final View container, final int position, final Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0) {
try{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.tabbed_main, null, false);
container.addView(view);
final Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
toolbar.setOnClickListener(HorizontalCoordinatorNtbAndTabbedActivity.this);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new TabbedActivity.SectionsPagerAdapter(getActivity().getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) view.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
return view;
} catch (ClassCastException e) {
Log.d(TAG, "Can't get the fragment manager with this");
return null;
}
}else if (position == 2) {
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp_list, null, false);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(
getBaseContext(), LinearLayoutManager.VERTICAL, false
)
);
recyclerView.setAdapter(new RecycleAdapter());
container.addView(view);
return view;
} else if (position == 4) {
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.test, null, false);
container.addView(view);
final TextView txt_test = (TextView) view.findViewById(R.id.txt_test);
txt_test.setOnClickListener(HorizontalCoordinatorNtbAndTabbedActivity.this);
return view;
} else {
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
}
});
final String[] colors = getResources().getStringArray(R.array.default_preview);
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_first),
Color.parseColor(colors[0]))
.title("MyHeart")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_second),
Color.parseColor(colors[1]))
.title("Cup")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_third),
Color.parseColor(colors[2]))
.title("Diploma")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_fourth),
Color.parseColor(colors[3]))
.title("Flag")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_fifth),
Color.parseColor(colors[4]))
.title("Medal")
.build()
);
navigationTabBar.setModels(models);
navigationTabBar.setViewPager(viewPager, 2);
//IMPORTANT: ENABLE SCROLL BEHAVIOUR IN COORDINATOR LAYOUT
navigationTabBar.setBehaviorEnabled(true);
navigationTabBar.setOnTabBarSelectedIndexListener(new NavigationTabBar.OnTabBarSelectedIndexListener() {
#Override
public void onStartTabSelected(final NavigationTabBar.Model model, final int index) {
}
#Override
public void onEndTabSelected(final NavigationTabBar.Model model, final int index) {
model.hideBadge();
}
});
navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
}
#Override
public void onPageScrollStateChanged(final int state) {
}
});
final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.parent);
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
for (int i = 0; i < navigationTabBar.getModels().size(); i++) {
final NavigationTabBar.Model model = navigationTabBar.getModels().get(i);
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
final String title = String.valueOf(new Random().nextInt(15));
if (!model.isBadgeShowed()) {
model.setBadgeTitle(title);
model.showBadge();
} else model.updateBadgeTitle(title);
}
}, i * 100);
}
coordinatorLayout.postDelayed(new Runnable() {
#Override
public void run() {
final Snackbar snackbar = Snackbar.make(navigationTabBar, "Coordinator NTB", Snackbar.LENGTH_SHORT);
snackbar.getView().setBackgroundColor(Color.parseColor("#9b92b3"));
((TextView) snackbar.getView().findViewById(R.id.snackbar_text))
.setTextColor(Color.parseColor("#423752"));
snackbar.show();
}
}, 1000);
Toast.makeText(HorizontalCoordinatorNtbAndTabbedActivity.this, "fab Button Click Event", Toast.LENGTH_SHORT).show();
}
});
final CollapsingToolbarLayout collapsingToolbarLayout =
(CollapsingToolbarLayout) findViewById(R.id.toolbar);
collapsingToolbarLayout.setExpandedTitleColor(Color.parseColor("#009F90AF"));
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.parseColor("#9f90af"));
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("HorizontalCoordinatorNtb Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.item_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.txt.setText(String.format("Navigation Item #%d", position));
}
#Override
public int getItemCount() {
return 20;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txt;
public ViewHolder(final View itemView) {
super(itemView);
txt = (TextView) itemView.findViewById(R.id.txt_vp_item_list);
}
}
}
// #Override
public void onClick(final View v) {
ViewCompat.animate(v)
.setDuration(200)
.scaleX(0.9f)
.scaleY(0.9f)
.setInterpolator(new HorizontalCoordinatorNtbAndTabbedActivity.CycleInterpolator())
.setListener(new ViewPropertyAnimatorListener() {
#Override
public void onAnimationStart(final View view) {
// Toast.makeText(HorizontalNtbActivity.this, "function onAnimationStart()",
// Toast.LENGTH_LONG).show();
// Log.d("function onAnimationStart", "function");
}
#Override
public void onAnimationEnd(final View view) {
switch (v.getId()) {
case R.id.txt_test:
// startActivity(
// new Intent(HorizontalNtbActivity.this, SamplesNtbActivity.class)
// );
Toast.makeText(HorizontalCoordinatorNtbAndTabbedActivity.this, "Test Button Click Event",
Toast.LENGTH_LONG).show();
//Toast.m
new SweetAlertDialog(HorizontalCoordinatorNtbAndTabbedActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
.setTitleText("Sweet!")
.setContentText("Here's a custom image test.")
.setCustomImage(R.drawable.custom_img)
.show();
final IOSTaoBaoDialog dialog = new IOSTaoBaoDialog(HorizontalCoordinatorNtbAndTabbedActivity.this, (View) view2);
dialog.show();
break;
default:
break;
}
}
#Override
public void onAnimationCancel(final View view) {
}
})
.withLayer()
.start();
}
private class CycleInterpolator implements android.view.animation.Interpolator {
private final float mCycles = 0.5f;
#Override
public float getInterpolation(final float input) {
return (float) Math.sin(2.0f * mCycles * Math.PI * input);
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Contact tab1Contact = new Tab1Contact();
return tab1Contact;
case 1:
Tab2Chat tab2Chat = new Tab2Chat();
return tab2Chat;
case 2:
Tab3Online tab3Online = new Tab3Online();
return tab3Online;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "CONTACT";
case 1:
return "CHAT";
case 2:
return "ONLINE";
}
return null;
}
}
}
Thank you very much
Your activity doesn't extend FragmentActivity from the support library, therefore you cannot call this method.
So you need something like that:
public class HorizontalCoordinatorNtbAndTabbedActivity extends FragmentActivity implements View.OnClickListener {
and then cast:
((HorizontalCoordinatorNtbAndTabbedActivity)getActivity()).getSupportFragmentManager()
Plus ViewPager inside ViewPager - it's not a good idea.
Try to use FragmentStatePagerAdapter instead of FragmentPagerAdapter. It could and possibly solve some possible problems.
Pass SupportFrogmentManager to FragmentStatePagerAdapter if inside it you are using fragments from support library. In other case - pass FragmentManager.
Depending on your view hierarchy you can try to get ChildFragmentManager.
Try to move ViewPager from fragment to activity.
I am trying to write different functionalities for my FloatingActionButton depending on the fragment that the mainActivity is currently hosting. Yet for for reason in my onClick() method, getSupportFragmentManager().findFragmentById() returns null.
I haven't seen any examples of this question implemented with a viewpager and I am curious if there is a different approach I have to take.
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
public class MainActivity extends FragmentActivity {
private Adapter mAdapter;
private ViewPager mViewPager;
private static FloatingActionButton bButton;
private static String UID;
private Intent intent;
public static String getUID(){
return UID;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new Adapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.vPager);
mViewPager.setAdapter(mAdapter);
intent = getIntent();
UID = intent.getStringExtra("uid");
bButton = (FloatingActionButton)findViewById(R.id.bButton);
bButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragContainer);
if(fragment == null){
Log.e("TAG","FRAGMENT IS NULL!!");
}
else{
Log.e("TAG","FRAGMENT IS NOT NULL!!");
}
}
});
}
}
NewsFeedFragment
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
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;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.mycompany.neighbors.R;
import com.mycompany.neighbors.SinglePost;
import java.util.ArrayList;
/**
* Created by joshua on 5/25/2016.
*/
public class NewsFeedFragment extends ListFragment implements AdapterView.OnItemClickListener{
private ListView lv;
private TextView tvUserName;
private TextView tvStatus;
private ArrayList<SinglePost> posts = new ArrayList<>();
private static final String POSTS_PATH = "MY_PATH";
private Firebase postsRef;
// private static final String FRAGMENT_POST = "post";
public void postFragment(){
Log.d("TAG", "Doing something else");
PostFragment postFragment = new PostFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragContainer,postFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onViewCreated(View v, Bundle s){
lv = getListView();
lv.setOnItemClickListener(this);
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_post_feed_item,parent,false);//changed
tvUserName = (TextView)v.findViewById(R.id.tvUN);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
postsRef = new Firebase(POSTS_PATH);
postsRef.addChildEventListener(new com.firebase.client.ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
SinglePost post = dataSnapshot.getValue(SinglePost.class);
post.setKey(dataSnapshot.getKey());
posts.add(0, post);
if(posts.size() > 0) {
PostAdapter adapter = new PostAdapter(posts);
setListAdapter(adapter);
}else{
Toast toast = Toast.makeText(getActivity(),"No data", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
SinglePost p = ((PostAdapter) getListAdapter()).getItem(position);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class PostAdapter extends ArrayAdapter<SinglePost>{
public PostAdapter(ArrayList<SinglePost> singlePost){
super(getActivity(),android.R.layout.simple_list_item_1,singlePost);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_post_feed_item,null);
}
SinglePost p = getItem(position);
TextView tvUserName = (TextView)convertView.findViewById(R.id.tvUN);
tvUserName.setText(p.getUserName());
TextView tvStatus = (TextView)convertView.findViewById(R.id.tvStatus);
tvStatus.setText(p.getStatus());
return convertView;
}
}
}
I have 2 other fragments but i'll post one as an example. Here is my adapter for the viewpager.
Adapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.mycompany.neighbors.Fragments.MapFragment;
import com.mycompany.neighbors.Fragments.NewsFeedFragment;
import com.mycompany.neighbors.Fragments.ProfileFragment;
/**
* Created by joshua on 5/25/2016.
*/
public class Adapter extends FragmentPagerAdapter {
private String Fragment[] = {"Posts" , "Map" , "Profile"};
public Adapter(FragmentManager fm){
super (fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new NewsFeedFragment();
case 1:
return new MapFragment();
case 2:
return new ProfileFragment();
default:
return null;
}
}
#Override
public int getCount(){return Fragment.length;}
#Override
public CharSequence getPageTitle(int position) {
return Fragment[position];
}
}
Please check below link, It has very good explanation for your problem:
http://tamsler.blogspot.in/2011/11/android-viewpager-and-fragments-part-ii.html
Or you can try below code snippet:
1.Where you add fragment in view pager or view pager adapter:
MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment,"Some Tag").commit();
2.To get the tag for the currently visible page, you then call:
int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);
3.and then get the fragment page:
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);
I know that people have asked this question, but I followed all the answers and I still have the same problem. I have two scripts One is the fragment manager (IngredientsActivity) and the other is the fragment (OtherList). The code is as follows
IngredientsActivity
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class IngredientsActivity extends FragmentActivity implements ActionBar.TabListener {
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.check_list);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText("Alcahol").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Juice").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Other").setTabListener(this));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); //OVERRIDE SAVE ON MAINCLASS
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
if (tab.getPosition() == 0) {
AlcoholList simpleListFragment = new AlcoholList();
getSupportFragmentManager().beginTransaction().replace(R.id.containert, simpleListFragment).commit();
}
else if (tab.getPosition() == 1) {
JuiceList androidlidt = new JuiceList();
getSupportFragmentManager().beginTransaction().replace(R.id.containert, androidlidt).commit();
}
else {
OtherList androidversionlist = new OtherList();
getSupportFragmentManager().beginTransaction().replace(R.id.containert, androidversionlist).commit();
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class DummySectionFragment extends Fragment {
public DummySectionFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
Bundle args = getArguments();
textView.setText(Integer.toString(args.getInt(ARG_SECTION_NUMBER)));
return textView;
}
}
}
OtherList
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
public class OtherList extends ListFragment{
MyCustomAdapter dataAdapter = null;
private ArrayList<String> recipesList;
private ArrayList<Items> stateList ;
public OtherList() {
setRetainInstance(true);
stateList = new ArrayList<Items>();
Items _states1 = new Items ("Gin",false);
stateList.add(_states1);
Items _states2 = new Items ("Ginger Liqueur",false);
stateList.add(_states2);
Items _states3 = new Items ("Citrus Vodka",false);
stateList.add(_states3);
Items _states4 = new Items ("Champagne",false);
stateList.add(_states4);
Items _states5 = new Items ("Coconut Rum",false);
stateList.add(_states5);
Items _states6 = new Items ("Pear Vodka",false);
stateList.add(_states6);
Items _states7 = new Items ("Rum",false);
stateList.add(_states7);
Items _states8 = new Items ("Tequila",false);
stateList.add(_states8);
Items _states9 = new Items ("Triple Sec",false);
stateList.add(_states9);
Items _states10 = new Items ("Kahlua",false);
stateList.add(_states10);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataAdapter = new MyCustomAdapter(this.getActivity(),R.layout.da_item, stateList);
setListAdapter(dataAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_fragment, container, false);
}
#Override
public void onListItemClick(ListView list, View v, int position, long id) {
}
private class MyCustomAdapter extends ArrayAdapter<Items>
{
private ArrayList<Items> stateList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Items> stateList)
{
super(context, textViewResourceId, stateList);
this.stateList = new ArrayList<Items>();
this.stateList.addAll(stateList);
}
private class ViewHolder
{
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.da_item, null);
holder = new ViewHolder();
holder.name = (CheckBox) convertView.findViewById(R.id.ingredientbox);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
Items _state = (Items) cb.getTag();
_state.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Items state = stateList.get(position);
holder.name.setText(state.getName());
holder.name.setChecked(state.isSelected());
holder.name.setTag(state);
return convertView;
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d("hey","SAVING"); //NOT SAVING
super.onSaveInstanceState(outState);
save();
outState.putStringArrayList("index", recipesList);
}
}
}
}
}
I found multiple suggestions that said to override the onSaveInstanceState , which I did and I found even more telling me to use setRetainInstance. I don't know why setRetainInstance state would be helpful if I want to save a value of a list. My question-Why Is it not calling the save in the OtherList class or whats a better method to implement if I want to save the values in the List View (in this case I am using checkboxes)
I had a similar problem where I was trying to get a Fragment to save its state but onSaveInstanceState() wasn't being called on FragmentTransaction.replace(). I was trying to find a solution for this and thought, if the Fragment itself can't save its own state then can't whatever is doing the replacing save it. So I did something like this:
In the Fragment have a method called getState() or whatever you want:
public Bundle getState()
{
// save whatever you would have in onSaveInstanceState() and return a bundle with the saved data
}
Then in the hosting object, save that bundle to its instance variables before replacing the Fragment and set the argument to that saved bundle when switching back.
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
// assume Fragment a exists and you're trying to save the state and "state" is an instance variable
state = a.getState();
ft.replace(android.R.id.content, b);
Then when swapping back to Fragment a you would pass the bundle as an argument.
a.setArguments(state);
ft.replace(android.R.id.content, a);
I didn't look into your code too deeply but it sounds similar to the problem I had from your description.
onSaveInstanceState() is only called when the Android system may need to recreate that particular instance of the Fragment. There are many instances of navigating away from the Fragment or even destroying the Fragment where it will not be called. Please consult the documentation for more information, please read the Activity.onSaveInstanceState() documentation as well since that applys here also: http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle)
http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)
EDIT: In your case, you must not recreate the fragment every time the user navigates back to the fragment. I recommend considering ViewPager and FragmentPagerAdapter to automatically manage the fragments. Also look at this post: ViewPager and fragments — what's the right way to store fragment's state?
I'm tring to make an app like google+ desing, with titlepager and switch between activities horizontally. I've implemnted this library for pager (https://github.com/JakeWharton/Android-ViewPagerIndicator) and it works fine. But now, I dont know how to set diferent activities.
This is my main class
package com.rbrlnx.controles;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.TitlePageIndicator;
public class ControlesDeAlcoholemiaActivity extends Activity {
static final int NUMERO_DE_PAGINAS = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Gestion del Pagindor
ViewPagerAdapter adapter = new ViewPagerAdapter( this );
ViewPager pager = (ViewPager)findViewById( R.id.viewpager );
TitlePageIndicator indicator = (TitlePageIndicator)findViewById( R.id.indicator );
pager.setAdapter( adapter );
indicator.setViewPager(pager,2);
//Gestion del ActionBar
ActionBar ab;
}
}
and this is the pageradapter
package com.rbrlnx.controles;
import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import com.viewpagerindicator.TitleProvider;
public class ViewPagerAdapter extends PagerAdapter implements TitleProvider
{
private static String[] titles = new String[]
{
"Comunes",
"Listado",
"Mapa"
};
private final Context context;
public ViewPagerAdapter( Context context )
{
this.context = context;
}
#Override
public String getTitle( int position )
{
return titles[ position ];
}
#Override
public int getCount()
{
return titles.length;
}
#Override
public Object instantiateItem( View pager, int position )
{
LinearLayout v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.comunes, null);
if (position == 0) {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.comunes, null);
} else if (position == 1) {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.listado, null);
} else {
v = (LinearLayout) LayoutInflater.from(this.context).inflate(R.layout.mapa, null);
}
((ViewPager) pager).addView(v, 0);
return v;
}
#Override
public void destroyItem( View pager, int position, Object view )
{
}
#Override
public boolean isViewFromObject( View view, Object object )
{
return view.equals( object );
}
#Override
public void finishUpdate( View view ) {}
#Override
public void restoreState( Parcelable p, ClassLoader c ) {}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate( View view ) {}
}
I can set the XML layout, but I don't know how to set the acitivy class. I think I must work with fragments but am not sure.