How to update fragment data using RecyclerView? - java

I have a ViewPager with 12 fragments. I need to get data from API and update the fragments when scrolling. How do I update the contents of fragment, with only one fragment updating for 12 pages?
My fragment layout fragment_item:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/surface">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/khaire"
android:gravity="center"
android:text="Overal Working Hour"
android:textColor="#color/colorPrimary"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:gravity="center"
android:padding="15dp"
android:text="January"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
My main activity code:
public class MainActivity extends AppCompatActivity {
private static final int num_pages = 12;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = findViewById(R.id.pager);
mPagerAdapter = new ScreenAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
private class ScreenAdapter extends FragmentStatePagerAdapter {
public ScreenAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return new SliderFragment();
}
#Override
public int getCount() {
return num_pages;
}
}
My SlideFragment class:
public class SliderFragment extends Fragment {
Toolbar toolbar;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_item,container,false);
return rootView;
}
Now I want to have same fragment while scrolling the page but with diff texts how could I do that... And if possible use RecyclerView also.

You could create a new Class (UpdatingFragment) with public abstract updateView(); that extends Fragment.
Create your SliderFragment by extending UpdatingFragment instead of Fragment
In the SliderFragment in onCreateView() at the end call updateView().
Write an overwrite method in your SliderFragment for what you need to update (anything you want to show on the UI)
Adjust your screenAdapter to return and take UpdatingFragment’s instead of Fragments.
Now whenever your fragments onCreateView gets called all their UI data gets updated, and if you create a list of SliderFragments and pass that into your adapter instead of creating new ones, you can just run a for loop over that list and call updateView() for each fragment.

Related

Pageviewer in a NestedScrollView not displaying text

I am using a PageViewer to display fragment's data, and whenever I put a TextView into the fragment's xml, it doesn't display when the app is being run. I put it in a NestedScrollView to put more widgets in then I could without it. I tried putting an ImageView in to see if it was removing everything but that worked fine, except it was a little laggy when changing fragments.
My code for my activity is
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.view_pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new VolleyballFragment(), "Volleyball");
adapter.addFragment(new SoftballFragment(), "Softball");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
my fragment codes are the nearly same so I will only provide 1
public class VolleyballFragment extends Fragment{
public VolleyballFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_volleyball, container, false);
}
}
and the activity xml file is
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"></androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabItem
android:id="#+id/softballFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Softball" />
<com.google.android.material.tabs.TabItem
android:id="#+id/volleyballFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vollyball" />
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
If you need any of the xml files or anything else please let me know.
I fallowed an older tutorial online since this is my first time using fragments and tabs, so I'm a little confused to begin with
Also sorry for the code being cut off and replaced as normal text
I tried your code everything else is fine but you're just missing layout_behavior on NestedScrollView.
After adding this property your code would look like this.
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
android:fillViewport="true">
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.core.widget.NestedScrollView>

RecyclerView: No adapter attached; skipping layout and java.lang.NullPointerException

I keep getting the error "E/RecyclerView: No adapter attached; skipping layout" when the RecyclerView list is shown. I'm getting data correctly from API but I got "void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference"
I know this question has been asked a lot before but I checked most of the questions and none has worked for me.
This is my fragment:
public class HomeFragment extends Fragment {
private View view;
private RecyclerView recyclerView;
private ArrayList<Result> arrayList;
private SwipeRefreshLayout refreshLayout;
private PostAdapter postAdapter;
private MaterialToolbar toolbar;
private SharedPreferences userPref;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.layout_home,container,false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
userPref = getContext().getApplicationContext().getSharedPreferences("user", Context.MODE_PRIVATE);
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerHome);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
refreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeHome);
toolbar =(MaterialToolbar) view.findViewById(R.id.toolbarHome);
((HomeActivity)getContext()).setSupportActionBar(toolbar);
getResults();
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getResults();
}
});
}
private void getResults() {//Working Fine}
}
My adapter:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostsHolder>{
private ArrayList<Result> list;
private Context context;
public PostAdapter(Context context, ArrayList<Result> list) {
this.list = new ArrayList<Result>(list);
this.context = context;
}
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_home, parent, false);
return new PostsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PostsHolder holder, int position) {
Result result = list.get(position);
holder.imgPostDate.setText(result.getDate());
}
#Override
public int getItemCount() {
return list.size();
}
public static class PostsHolder extends RecyclerView.ViewHolder{
private TextView imgPostProfile,imgPostName,imgPostDate;
private ImageButton btnPostOption;
public PostsHolder(#NonNull View itemView) {
super(itemView);
imgPostProfile =(TextView) itemView.findViewById(R.id.imgPostProfile);
imgPostName = (TextView)itemView.findViewById(R.id.imgPostName);
imgPostDate =(TextView) itemView.findViewById(R.id.imgPostDate);
btnPostOption =(ImageButton) itemView.findViewById(R.id.btnPostOption);
}
}
}
I modified my code according to the answers I found to similar questions but none of them worked.
layout_home
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.MaterialToolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbarHome"
android:elevation="1dp"
android:theme="#style/Theme.MaCoSISBottomAppBar"
app:title=""
tools:targetApi="lollipop">
<!-- <ImageView-->
<!-- android:layout_width="100dp"-->
<!-- android:layout_height="40dp"-->
<!-- android:src="#drawable/logo_dark"/>-->
</com.google.android.material.appbar.MaterialToolbar>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:id="#+id/swipeHome"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerHome"
android:layout_height="match_parent"
android:layout_width="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
layout_post
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:clickable="true"
android:focusable="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<TextView
android:id="#+id/imgPostProfile"
android:layout_width="60sp"
android:layout_height="60sp"
android:background="#drawable/shape_circle"
android:text="MC"
android:gravity="center"
android:textColor="#color/colorWhite"
android:textSize="14sp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:paddingLeft="6dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgPostName"
android:text="BBAD1252 Social Harmony and Business Skills Development"
android:textColor="#color/colorBlack"
android:textSize="14sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgPostDate"
android:text="12 Novermber 2020"
android:textColor="#color/colorLightGrey"
android:textSize="12dp" />
</LinearLayout>
<ImageButton
android:id="#+id/btnPostOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:background="#android:color/transparent"
android:layout_gravity="center_vertical"
android:src="#drawable/ic_baseline_more_vert_24"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#color/colorLightGrey"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
In onCreateViewHolder you inflated the wrong xml. It should've been R.layout.layout_post
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_post, parent, false);
return new PostsHolder(view);
}
To prevent from error E/RecyclerView: No adapter attached; skipping layout, you should call recyclerView.setAdapter(adapter); inside your init(); method.
Then after you have your data you should notify the adapter in order to display your data by calling adapter.notifyDataSetChanged(); or using any other notify methods. Check this answer for other notify methods.
If your getResults() is where you're calling your recyclerview.setAdapter(), you're calling setAdapter too late. You need to make sure your adapter is set during onCreateView() so that the Recyclerview isn't being skipped while drawing the layout.
No Adapter Attached; Skipping layout:
you should setadapter in your main thread methods of fragment; then add or update data to adapter
Nullpointer at settext [at adapter]: In onCreateViewHolder you inflated the wrong xml. It should be R.layout.layout_post instead of R.layout.layout_home

Change toolbar according to Fragment

I want to change the top toolbar according to clicked fragment but it seems not working for me.
What I want is when I click the fragment, the top toolbar should change. For example, add a Add button and change the title of the toolbar for Create Fragment.
Fragment.java
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
Toolbar toolbar123 = (Toolbar) v.findViewById(R.id.toolbar123);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar123);
//((MainActivity) getActivity()).getSupportActionBar().hide();
return v;
}
Fragment XML
<FrameLayout 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="com.example.rick.check_in.ui.EventCreatedFragment">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar123"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#131313"
android:minHeight="?attr/actionBarSize">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#00aaaaaa">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:text="Delete"
android:textColor="#fff"
android:textSize="16dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
You can do it like this way. onAttach(Activity) called once the fragment is associated with its activity.
public class YourFragment extends Fragment {
private MainActivity mainActivity;
private Toolbar toolbar123;
public YourFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mainActivity = (MainActivity)activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
toolbar123 = (Toolbar)v.findViewById(R.id.toolbar123);
setupToolbar();
return v;
}
private void setupToolbar(){
toolbar123.setTitle(getString("Your Fragment Title"));
mainActivity.setSupportActionBar(toolbar123);
}
}

viewPager not displaying fragment

for this project, I have tabs that have to display something under them and i'm using view pager but for some reason, the fragment layout isn't showing up on screen. I get a blank screen but there is no error or anything. I have been googling and searching for hours now and even started a new project just to make sure it was not a build error but still no luck in finding a solution to my problem.
I have done examples like this many times and used the exact same steps but for some reason, it just isn't working this time. Any help would be greatly appreciated
Here is my mainActivity class
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager myViewPager;
SlidingTabLayout mySlidingTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myViewPager = (ViewPager) findViewById(R.id.viewPager);
myViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), this));
mySlidingTabs = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mySlidingTabs.setViewPager(myViewPager);
}
}
Here is my custom adapter class
public class MyPagerAdapter extends FragmentPagerAdapter {
private Context context;
private String[] tabNames = {"Beverages", "Deli & Bakery", "Fresh Produce", "Health & Beauty", "Meat & Seafood", "Natural Foods", "Pet Care"};
public MyPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new Beverages();
}
else if (position == 1) {
return new DeliBakery();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return tabNames[position];
}
}
Here is my main activty.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="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar_layout"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
<!-- The Sliding tab -->
<bello.myapplication.SlidingTabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sliding_tabs"/>
<!-- The pager that allows us to swipe between fragments -->
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
and here is one of my tab's xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab fragment 1"
android:textSize="50dp"
android:padding="5dp" />
</RelativeLayout>
Here is one of my fragment classes
public class Beverages extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.beverages_tab, container, false);
return view;
}
}
When something strange like this happens, try to use Log.i("title", "message") to track if every class/methods are being called.
In your case, it seens that your viewpager isn't in the screen.
If I understood your code, your <include> tag is including the second xml code you posted right?
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab fragment 1"
android:textSize="50dp"
android:padding="5dp" />
</RelativeLayout>
It looks like your layout_height="match_parent" is filling all the space on your screen, giving no space to your ViewPager being inflated by the system, try to change it to layout_height="wrap_content and you should be done.
If not, try to change the background of your ViewPager to check if it is on the screen and is not being hided by something else.
Figured out the problem. The viewpager background color and the background color of the tabs where the same so it made it look like there was a black activity. So for anyone else out there with the same problem, try changing either the text color of your tabs.xml or change the background of your viewpager

ViewPager and Fragments: Why do I always see the same thing?

I have created a ViewPager with three "pages". The code is this
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_tab_strip);
FragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
getSupportFragmentManager());
viewPager.setAdapter(fragmentPagerAdapter);
pagerTabStrip.setDrawFullUnderline(true);
pagerTabStrip.setTabIndicatorColor(Color.DKGRAY);
}
}
MyFragmentPageAdapter.java
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private String[] pageTitle = {
"Page1", "Page2", "Page3"
};
public MyFragmentPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putString("pageIndex", Integer.toString(position + 1));
fragment.setArguments(arguments);
return fragment;
}
#Override
public int getCount() {
return pageTitle.length;
}
#Override
public CharSequence getPageTitle(int position) {
return pageTitle[position];
}
}
PageFragment.java
public class PageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);
return view;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33B5E5"
android:textColor="#FFFFFF"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_page.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:textSize="16sp"
android:textStyle="italic"
android:gravity="center_horizontal"
android:textColor="#color/red"
android:text="#string/inf" />
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="60dp"
android:textSize="28sp"
android:gravity="center_horizontal"
android:textStyle="bold"
android:text="#string/ben" />
<TextView
android:id="#+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="130dp"
android:gravity="center_horizontal"
android:textSize="18sp"
android:text="Prova"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_centerInParent="true"
android:text="#string/verifica" />
</RelativeLayout>
But now i visualize in all three pages the same thing. If I for example on page 2 I want a TextView with the text "This is the 2 page" and on the third page a TextView with the text "This is the page 3" and in the first page two TextView with the button ... how can I? I'm going crazy, please let pass me the code to do this thing. Please.
Once you inflate PageFragment's layout you need to get a reference of the TextView so you can display the position on it via the Bundle you are passing using setArguments(). Use your view variable inside onCreateView() to get a reference of the TextView. (i.e. view.findViewById()). Then use getArguments() in your PageFragment to retrieve the Bundle with that has position, and set the TextView to that value.
this is a good example for what you want.
Just create a function in your page fragment class to configure elements and modify onCreateView to attach childs.
public class PageFragment extends Fragment {
TextView tv1 ;
// ...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);
/// Attach your childs
tv1 = view.findViewById(R.id.textView1);
return view;
}
public void configure(int position) {
tv1 .setText("This is "+ position);
}
}
Then just call the function configure in getItem function
#Override
public Fragment getItem(int position) {
PageFragment fr = new PageFragment();
fr.configure(position + 1);
return fr;
}

Categories

Resources