This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 4 years ago.
Today I'm having this issue with my application; I want to say that I read almost ALL the other questions here on StackOverflow but nothing, always the same problem.
homepage.java (main class)
public class homepage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_homepage, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch(getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1:
rootView = inflater.inflate(R.layout.fragment_homepage, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_adsl, container, false);
break;
case 4:
rootView = inflater.inflate(R.layout.fragment_aiuto, container, false);
break;
}
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
}
}
MyAdapter.java (default code from Android Studio Guide)
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public MyViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
TextView v = (TextView) LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
And finally, one of the fragment that I'm using:
fibra.java
public class fibra extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RecyclerView recyclerView;
private MyAdapter adapter;
private LinearLayoutManager llm;
String [] prova={"prova1","prova2","prova2","prova2","prova2","prova2","prova2"};
public fibra() {
}
public static fibra newInstance(String param1, String param2) {
fibra fragment = new fibra();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.my_activity); (doesn't work "cannot resolve method")
recyclerView.setHasFixedSize(true); //per migliorare performance
llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
adapter = new MyAdapter(prova);
recyclerView.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
return rootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Here:
//setContentView(R.layout.my_activity); (doesn't work "cannot resolve method")
It's like inflating a layout inside an Activity which you already have onCreateView and in a Fragment.
Change the first codes to :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
Then, initialize RecyclerView inside onCreateView().
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fibra, container, false);
// Here you should initialize RecyclerView and other widgets by rootView.findViewById and etc
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true); //per migliorare performance
llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
adapter = new MyAdapter(prova);
recyclerView.setAdapter(adapter);
return rootView;
}
You forget to add tablaylout.setupWithViewPager(mViewPager); in your homepage.java
Related
I am trying to implement a sales app with 3 stages, whereby a user first adds the items, views the cart to checkout and prints a receipt. The first stage is done and works well. I am implementing this using one Activity with a tabbed layout and 3 fragments for each of the tabs.
On the activity for viewing the cart, I am using a RecyclerView which loads well when the activity is created, but once I add an item and try to view the list, there is no update. However, when I print the item list, the item has been added.
I have tried to update the RecyclerView using notifyDataSetChanged() but it gives me a null pointer exception. I have and tried several solutions but none has worked. Kindly assist.
Below is my code.
NewSaleActivity.java
public class NewSaleActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private ActivityNewSaleBinding binding;
DrawerLayout drawerLayout;
NavigationView navigationView;
TabLayout tabLayout;
Context context;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityNewSaleBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Toolbar toolbar = findViewById(R.id.new_sale_toolbar);
toolbar.setTitle(R.string.new_sale);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.new_sale_drawer);
navigationView = findViewById(R.id.new_sale_navigation);
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_sale);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
context = getApplicationContext();
tabLayout = findViewById(R.id.tab_layout);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
viewPager = binding.viewPager;
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(1);
TabLayout tabs = binding.tabLayout;
tabs.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//When cart tab is selected
if(tab.getPosition() == 1) {
CartFragment cartFragment = new CartFragment();
cartFragment.loadItemsInCart();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
Intent mainIntent = new Intent(NewSaleActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
break;
case R.id.nav_inventory:
Intent inventoryIntent = new Intent(NewSaleActivity.this, InventoryActivity.class);
startActivity(inventoryIntent);
finish();
break;
case R.id.nav_sale:
break;
case R.id.nav_logout:
UserLogout.userLogout(NewSaleActivity.this);
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
CartFragment.java
public class CartFragment extends Fragment {
RecyclerView cartRecyclerView;
TextInputLayout grossTotalInput, discountInput, netTotalInput;
Button checkoutButton;
CartItemAdapter cartItemAdapter;
ArrayList<CartItem> cartItemList;
public CartFragment() {
// Required empty public constructor
}
public static CartFragment newInstance() {
CartFragment fragment = new CartFragment();
Bundle args = new Bundle();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
cartRecyclerView = view.findViewById(R.id.cart_recycler_view);
grossTotalInput = view.findViewById(R.id.gross_total_input);
discountInput = view.findViewById(R.id.discount_input);
netTotalInput = view.findViewById(R.id.net_total_input);
checkoutButton = view.findViewById(R.id.checkout_button);
Paper.init(requireContext());
cartItemList = Paper.book().read("cartItems", new ArrayList<CartItem>());
cartRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
cartItemAdapter = new CartItemAdapter(cartItemList);
cartRecyclerView.setAdapter(cartItemAdapter);
checkoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkoutOrder();
}
});
cartItemAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_cart, container, false);
}
public void loadItemsInCart() {
ArrayList<CartItem> cartList = Paper.book().read("cartItems", new ArrayList<CartItem>());
for(CartItem cartItem : cartList) {
Log.d("cartItem", cartItem.getItemName());
}
cartItemAdapter.updateCartList(cartList);
Log.d("loadItemsInCart", "Load Items In Cart is triggered");
}
CartItemAdapter.java
public class CartItemAdapter extends RecyclerView.Adapter<CartItemAdapter.ViewHolder> {
private final ArrayList<CartItem> cartItems;
public CartItemAdapter(ArrayList<CartItem> cartItems) {
this.cartItems = cartItems;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemCode, itemName, quantity, price;
public ViewHolder(View itemView) {
super(itemView);
this.itemCode = itemView.findViewById(R.id.item_code);
this.itemName = itemView.findViewById(R.id.item_name);
this.quantity = itemView.findViewById(R.id.item_quantity);
this.price = itemView.findViewById(R.id.item_price);
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View cartListItem = layoutInflater.inflate(R.layout.add_to_cart_item, parent, false);
return new CartItemAdapter.ViewHolder(cartListItem);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.itemCode.setText(cartItems.get(position).getItemCode());
holder.itemName.setText(cartItems.get(position).getItemName());
holder.quantity.setText(cartItems.get(position).getQuantity().toString());
holder.price.setText(cartItems.get(position).getTotalAmount().toString());
}
#Override
public int getItemCount() {
return cartItems.size();
}
#SuppressLint("NotifyDataSetChanged")
public void updateCartList(ArrayList<CartItem> cartList) {
cartItems.clear();
this.cartItems.addAll(cartList);
notifyDataSetChanged();
}
}
The error message that I get is as below
java.lang.NullPointerException: Attempt to invoke virtual method 'void app.project.jsml_sales_app.adapters.CartItemAdapter.updateCartList(java.util.ArrayList)' on a null object reference
at app.project.jsml_sales_app.activities.fragments.CartFragment.loadItemsInCart(CartFragment.java:128)
at app.project.jsml_sales_app.activities.NewSaleActivity$1.onTabSelected(NewSaleActivity.java:78)
at com.google.android.material.tabs.TabLayout.dispatchTabSelected(TabLayout.java:1993)
at com.google.android.material.tabs.TabLayout.selectTab(TabLayout.java:1986)
I want to make CardViews visible on a RecyclerView inside a Fragment, but all I get is a infinite loading sign and no cardviews are being showed. I'm very new to Android Programming so please be kind..
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentPage fragment = new FragmentPage();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.placeholder, fragment);
fragmentTransaction.commit();
ViewPager viewpager = findViewById(R.id.viewpager);
viewpager.setOffscreenPageLimit(1);
SwipeAdapter adapter = new SwipeAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setPageTransformer(true, new DepthPageTransformer());
viewpager.setCurrentItem(0);
}
}
This is my Adapter class(I followed a Tutorial)
public class ListAdapterIT extends RecyclerView.Adapter {
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
private class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mImageView;
public ListViewHolder (View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image2);
itemView.setOnClickListener(this);
}
public void BindViewHolder(int position) {
mImageView.setImageResource(OurData.picturePath[position]);
}
public void onClick(View view) {
}
}
}
This is my Fragment I also think the Problem is in that class
public class FragmentPage extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page_fragment, container, false);
ArrayList<Integer> items = new ArrayList<>();
items.add(R.layout.example_item);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.listRecyclerView);
ListAdapterIT listAdapter = new ListAdapterIT() {};
recyclerView.setAdapter(listAdapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}
i have a Fragment(C) with a ViewPager(Adapter) with 2 Fragments(A/B).
When i call the Fragment once time, they load fine.
But when i call the Fragment(C) the secend time, the Fragment A and B dont call the View onCreateView methode and the isnĀ“t loaded.
The Fragment C is called with Fragmetnmanger:
FragmentC fragment = new FragmentC();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.adressenmdf_detail_container, fragment).addToBackStack(null).commit();
Fragment C
public BelegeDetails(){
}
#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.activity_belege_details, container, false);
//TODO Actionbar noch anpassen
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
The Setups from Fragment C
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
adapter.addFragment(new BelegeDetails1(),"Details" );
adapter.addFragment(new BelegeDetailsPos(), "Positionen");
viewPager.setAdapter(adapter);
}
private void setupTabIcons() {
tabLayout.getTabAt(1).setIcon(R.drawable.ic_belege);
}
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);
}
}
The Fragment A BelegDetails1 und the Fragment B BelegDetailsPos are normal Fragment Classes like:
public BelegeDetails1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState.......
try changing this:
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
with:
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
As you are nesting fragments, you need to use getChildFragmentManager() instead of getFragmentManager()
When switching from one fragment to another fragment (within the second tab of my application), my second fragment is blank. I have tried the solutions linked here, but none seem to work:
Transaction of fragments in android results in blank screen
Android: Getting white screen with fragment transaction
MainActivity:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter, and add pages.
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter.addPage(new Received());
mSectionsPagerAdapter.addPage(new Send());
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_alert_partners, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_received, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2) {
View rootView = inflater.inflate(R.layout.fragment_send, container, false);
return rootView;
}
else {//main empty fragment in case of error. Never used in normal behaviour.
View rootView = inflater.inflate(R.layout.fragment_alert_partners, container, false);
return rootView;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//Create an Array list that will hold the pages.
ArrayList<Fragment> pages = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return pages.get(position);
}
//Add a page
public void addPage(Fragment f) {
pages.add(f);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Send";
}
return null;
}
}
}
SendFragment:
public class Send extends Fragment {
private OnFragmentInteractionListener mListener;
private TextView text1;
public Send() {
// 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
View v = inflater.inflate(R.layout.fragment_send, container, false);
//Need getView() for fragment since setContentView must be set first but is not possible in fragment.
text1 = (TextView)v.findViewById(R.id.textview1);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Send2 send2 = new Send2();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.hide(Send.this);
fragmentTransaction.add(android.R.id.content, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return v;
}
public interface OnFragmentInteractionListener {
}
}
Send2Fragment:
public class Send2 extends Fragment {
private OnFragmentInteractionListener mListener;
public Send2() {
// 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
final View v = inflater.inflate(R.layout.fragment_send2, container, false);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
}
}
Had to add a framelayout at the end of the layout code for the fragment I was replacing:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/send1frameLayoutId">
</FrameLayout>
Then used this code to switch to a fragment in the same tab of the previous fragment:
Fragment send2 = new Send2();
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.send1frameLayoutId, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
I have a swipe Activity, with 2 swipe pages, I added the content for the first page and on the second page the content is duplicated, how can I set different content to the second page in my swipe view?
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
return rootView;
}
}
}
Android Developers site really has very good explanation of ViewPager. You should check it out:
http://developer.android.com/training/animation/screen-slide.html
Here is an example I wrote:
activity_screen_slide.xml
<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" />
Java Code:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...
public class ScreenSlidePagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 2;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
//Create these fragments with your preferable names
switch (position) {
case 0:
return new ScreenSlidePageFragment();
case 1:
return new ScreenSlidePageFragment2();
default:
break;
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
And here is one of your views that should look like it where fragment_ screen_slide_page is one of your layouts:
import android.support.v4.app.Fragment;
...
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
You should really read the android developers site for further details.
You can return different fragments like this:
#Override
public Fragment getItem(int position) {
if (position == 0) {
return PlaceholderFragment.newInstance(position + 1);
} else {
return anotherFragment.newInstance();
}
}
If you want to use the same Fragment, you can change the content depending on the position you are passing to the fragment.