i have been working on app (Question Answer based) . I have included view pager to swipe the image but it's only swiping same image .
code of class which call a class (where view pager is included in activity)
package com.example.joshiyogesh.puzzle;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class ExerciseOneQuestionList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_one_question_list);
}
public void questionOne(View view) {
Intent intent = new Intent(getApplicationContext(),ExerciseOneQuestions.class);
intent.putExtra("question_index",0);
startActivity(intent);
}
}
ExerciseOneQuestion.java
package com.example.joshiyogesh.puzzle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ExerciseOneQuestions extends AppCompatActivity {
ViewPager viewPager;
public int questionIndexReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercise_one_questions);
questionIndexReceive = getIntent().getIntExtra("question_index",1);
// questionIndexReceive =Integer.parseInt(getIntent().getStringExtra("question_index"));
viewPager = (ViewPager)findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
pager Adapter class
package com.example.joshiyogesh.puzzle;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
position = new ExerciseOneQuestions().questionIndexReceive;
Fragments fragments = new Fragments();
Bundle bundle = new Bundle();
bundle.putInt("question_no",position);
fragments.setArguments(bundle);
return fragments;
}
#Override
public int getCount() {
return 2;
}
}
fragments class
public class Fragments extends Fragment {
ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater , ViewGroup container ,
Bundle savedInstanceState){
int [] image_index = {R.drawable.eightypageanswer1,R.drawable.eightypageanswer8};
Bundle bundle = getArguments();
int message = bundle.getInt("question_no");
View rootView = inflater.inflate(R.layout.fragments,container,false);
imageView = (ImageView) rootView.findViewById(R.id.imageQuestions);
imageView.setImageResource(image_index[message]);
return rootView;
}
}
for testing purpose I have considered only two images in integer, But its always swiping same image i.e first image.
instead of changing "question_index" in ExerciseOneQuestionList.java
here ...
public void questionOne(View view) {
Intent intent = new Intent(getApplicationContext(),ExerciseOneQuestions.class);
intent.putExtra("question_index",0);
startActivity(intent);
}
couldn't understand why its always showing same image ?
It seems that problem is in line
position = new ExerciseOneQuestions().questionIndexReceive;
It seems that position is always set on the same number.
I really dont know what you are doing with this " new ExerciseOneQuestions().questionIndexReceive;" line. But in standard way you should have make two fragments then add these fragments to your adapter. Rest of thing will be done by adapter , following rough code may help you :
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position); // Which Fragment should be dislpayed by the viewpager for the given position
}
#Override
public int getCount() {
return mFragments.size();
}
}
Make two fragments object in class add them in adapter by calling addFragment method and then setadapter.
Related
I have a Card View in a layout that has a two Text Views and an Image View and i have a Recycler View that uses the Card View to set items. What i want to achieve is to launch a Bottom Sheet when the Card View is tapped
Here is the code in Main Activity
Code for List
List<Item> lstItem;
lstItem = new ArrayList<>();
lstItem.add(new Item("Samsung","Smartphones","QualitlstItem = new ArrayList<>();y Samsung Smartphones",R.drawable.samsung,"21000"));
lstItem.add(new Item("Lenovo","Smartphones","Quality Lenovo smartphones",R.drawable.lenovo,"15000"));
Code for attaching Recycler View Adapter to Main Activity
FragmentManager fragmentManager = getSupportFragmentManager();
RecyclerViewAdapter2 mainAdapter2 = new RecyclerViewAdapter2(lstItem,fragmentManager);
mainRecyclerView.setLayoutManager(new GridLayoutManager(this,3));
mainRecyclerView.setAdapter(mainAdapter2);
Recycler View Adapter 2 Code
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewAdapter2 extends RecyclerView.Adapter<RecyclerViewAdapter2.MyViewHolder> {
private Context context;
private List<Item> data;
private FragmentManager fragmentManager;
public RecyclerViewAdapter2(List<Item> data, FragmentManager fragmentManager) {
this.data = data;
this.fragmentManager = fragmentManager;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_items, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.tv_item_title.setText(data.get(position).getTitle());
holder.price.setText(data.get(position).getPrice());
holder.item_thumbnail.setImageResource(data.get(position).getThumbnail());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv_item_title;
TextView price;
ImageView item_thumbnail;
CardView cardView;
public MyViewHolder(View itemView){
super(itemView);
tv_item_title = itemView.findViewById(R.id.itemTitleId);
price = itemView.findViewById(R.id.priceId);
item_thumbnail = itemView.findViewById(R.id.itemThumbnailId);
cardView = itemView.findViewById(R.id.cardView);
}
}
}
This is where am having a problem: Launching Bottom Sheet on Card View Click:
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
BottomSheetFragment Code;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
public class BottomSheetFragment extends BottomSheetDialogFragment {
public BottomSheetFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.bottomsheet1, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//String s=getArguments().getString("myString");
}
}
I have tried the following inside onBindViewHolder:
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.tv_item_title.setText(data.get(position).getTitle());
holder.price.setText(data.get(position).getPrice());
holder.item_thumbnail.setImageResource(data.get(position).getThumbnail());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AppCompatActivity appCompatActivity = new AppCompatActivity();
FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
bottomSheetFragment.show(fragmentManager, bottomSheetFragment.getTag());
}
});
}
Here is the Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: manu.apps.victortestapp, PID: 16271
java.lang.IllegalStateException: Activity has been destroyed
at androidx.fragment.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2114)
at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:683)
at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:637)
at androidx.fragment.app.DialogFragment.show(DialogFragment.java:144)
at manu.apps.victortestapp.RecyclerViewAdapter2$1.onClick(RecyclerViewAdapter2.java:52)
at android.view.View.performClick(View.java:6726)
at android.view.View$PerformClick.run(View.java:25434)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6524)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:451)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
I want to open BottomSheet when the Card View inside the Recycler View is tapped
In your onClick Listener, you need to use the fragmentManager you are passing to the Adapter. Instead you use getSupportFragmentManager(). After changing this it works for me.
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
// <-- Here change getSupportFragmentManager() to fragmentManager
bottomSheetFragment.show(fragmentManager, bottomSheetFragment.getTag());
}
});
to call BottomSheetDialog Fragment from RecyclerView.Adapter. Try this it worked fine for me.
DialogFragment bottomSheetDialogFragment = new BottomsheetDialog();
bottomSheetDialogFragment.show(((FragmentActivity)mContext).getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
You can't do this:
AppCompatActivity appCompatActivity = new AppCompatActivity();
FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
bottomSheetFragment.show(fragmentManager, bottomSheetFragment.getTag());
You should create a new Activity ( a new class ) that will contain your BottomSheetFragment and start that activity using an intent.
I have been researching how to accomplish an activity with tabs and have gotten very close to completion. Unfortunately, I have hit a bit of a roadblock.
After following a great guide, I created an interactive activity with a tabLayout and a ViewPager to display the fragment.
Each tab displays the same layout, which is a column of TextViews on the left which keep their default value, and another column of TextViews that need to get their value from different locations.
As a test, I had each tab send different text values to their respective TextViews (example Tab #1 was assigned to use "Downstairs", #2 was assigned to use "Upstairs") - which is accomplished through the onTabSelected listener.
The issue I am running in to, is when the text is assigned to the TextViews. It never displays when the tab is selected. It sometimes displays on the next tab I open. It also sometimes displays Tab 1 assignment values in Tab 3 after I had already opened tab 2 before opening tab 3.
Every other TextView I have worked with updates right away when I use setText(). However, I am very new to using Tab Activities, so I very well could be messing something up.
Distribution.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class Distribution extends FragmentActivity {
private Context context;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distribution);
context = this;
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
TabFragment.cream.setText("Downstairs");
TabFragment.freshnessBottles.setText("Downstairs");
TabFragment.soap.setText("Downstairs");
TabFragment.paperCups.setText("Downstairs");
TabFragment.shortStirSticks.setText("Downstairs");
TabFragment.longStirSticks.setText("Downstairs");
TabFragment.cafeRoyale.setText("Downstairs");
TabFragment.hotChocolate.setText("Downstairs");
TabFragment.equal.setText("Downstairs");
TabFragment.sugar.setText("Downstairs");
TabFragment.greenTea.setText("Downstairs");
TabFragment.orangePekoe.setText("Downstairs");
break;
case 1:
TabFragment.cream.setText("Upstairs");
TabFragment.freshnessBottles.setText("Upstairs");
TabFragment.soap.setText("Upstairs");
TabFragment.paperCups.setText("Upstairs");
TabFragment.shortStirSticks.setText("Upstairs");
TabFragment.longStirSticks.setText("Upstairs");
TabFragment.cafeRoyale.setText("Upstairs");
TabFragment.hotChocolate.setText("Upstairs");
TabFragment.equal.setText("Upstairs");
TabFragment.sugar.setText("Upstairs");
TabFragment.greenTea.setText("Upstairs");
TabFragment.orangePekoe.setText("Upstairs");
break;
case 2:
TabFragment.cream.setText("Shipping");
TabFragment.freshnessBottles.setText("Shipping");
TabFragment.soap.setText("Shipping");
TabFragment.paperCups.setText("Shipping");
TabFragment.shortStirSticks.setText("Shipping");
TabFragment.longStirSticks.setText("Shipping");
TabFragment.cafeRoyale.setText("Shipping");
TabFragment.hotChocolate.setText("Shipping");
TabFragment.equal.setText("Shipping");
TabFragment.sugar.setText("Shipping");
TabFragment.greenTea.setText("Shipping");
TabFragment.orangePekoe.setText("Shipping");
break;
case 3:
TabFragment.cream.setText("Solutions");
TabFragment.freshnessBottles.setText("Solutions");
TabFragment.soap.setText("Solutions");
TabFragment.paperCups.setText("Solutions");
TabFragment.shortStirSticks.setText("Solutions");
TabFragment.longStirSticks.setText("Solutions");
TabFragment.cafeRoyale.setText("Solutions");
TabFragment.hotChocolate.setText("Solutions");
TabFragment.equal.setText("Solutions");
TabFragment.sugar.setText("Solutions");
TabFragment.greenTea.setText("Solutions");
TabFragment.orangePekoe.setText("Solutions");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
TabFragment.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;
public class TabFragment extends Fragment {
protected static final String ADMIRAL_DOWNSTAIRS_PREFS_NAME = "AdmiralDownstairsPrefsFile";
protected static final String ADMIRAL_UPSTAIRS_PREFS_NAME = "AdmiralUpstairsPrefsFile";
protected static final String ADMIRAL_SHIPPING_PREFS_NAME = "AdmiralShippingPrefsFile";
protected static final String SOLUTIONS_PREFS_NAME = "SolutionsPrefsFile";
protected static SharedPreferences AdmiralDownstairsData;
protected static SharedPreferences AdmiralUpstairsData;
protected static SharedPreferences AdmiralShippingData;
protected static SharedPreferences SolutionsData;
protected static SharedPreferences.Editor editor;
int position;
protected static TextView cream;
protected static TextView freshnessBottles;
protected static TextView soap;
protected static TextView paperCups;
protected static TextView shortStirSticks;
protected static TextView longStirSticks;
protected static TextView cafeRoyale;
protected static TextView hotChocolate;
protected static TextView equal;
protected static TextView sugar;
protected static TextView greenTea;
protected static TextView orangePekoe;
public static Fragment getInstance(int position) {
Bundle bundle = new Bundle();
bundle.putInt("pos", position);
TabFragment tabFragment = new TabFragment();
tabFragment.setArguments(bundle);
return tabFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt("pos");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
cream = view.findViewById(R.id.lblCreamValue);
freshnessBottles = view.findViewById(R.id.lblMilkValue);
soap = view.findViewById(R.id.lblSoapValue);
paperCups = view.findViewById(R.id.lblCupValue);
shortStirSticks = view.findViewById(R.id.lbl4_5StirValue);
longStirSticks = view.findViewById(R.id.lbl7StirValue);
cafeRoyale = view.findViewById(R.id.lblCafeRoyaleValue);
hotChocolate = view.findViewById(R.id.lblHotChocValue);
equal = view.findViewById(R.id.lblEqualValue);
sugar = view.findViewById(R.id.lblSugarValue);
greenTea = view.findViewById(R.id.lblGreenTeaValue);
orangePekoe = view.findViewById(R.id.lblOrangePekoeValue);
}
}
ViewPagerAdapter.java
package local.mobileapps.bryandouglas.supremeshoppinglist;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class ViewPagerAdapter extends FragmentPagerAdapter {
private String title[] = {"Admiral - Downstairs", "Admiral - Upstairs", "Admiral - Shipping", "Solutions"};
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return TabFragment.getInstance(position);
}
#Override
public int getCount() {
return title.length;
}
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
I was attempting to design it in a way that uses SharedPreferences to store and read persistent data. There is a specific sharedPrefs files for each corresponding tab. You will notice that sharedPrefs have not been implemented, and is that way as I wanted to test with just basic setText.
I took the tab activity start and took the tabs out of the code and the floating button. I created a new fragment to replace the placeholder one. I just don't understand how to get it to swipe to a different fragment then the replacement placeholder one. Not sure if I should continue this or try to do a different viewpager. Any help in what to change, where to learn this particular thing, or any other help would be greatly appreciated. Trying to program an app for my union and bring it closer to being modern. Thank you.
package myapp.app;
import android.support.v7.app.AppCompatActivity;
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.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ContactActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public static class fragment_contact extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public fragment_contact() {
}
public static fragment_contact newInstance(int i) {
fragment_contact fragment = new fragment_contact();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, i);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contact, container, false);
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public fragment_contact getItem(int i) {
return new fragment_contact();
}
#Override
public int getCount() {
return 11;
}
}
}
When I select tab 3 my listview appears, yet when I select tab 1 and reselect tab 3, the listview doesn't appear.
Why is this?
https://github.com/jdavey1996/News-Android-App
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Local"));
tabLayout.addTab(tabLayout.newTab().setText("Top rated"));
tabLayout.addTab(tabLayout.newTab().setText("All"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
package com.josh_davey.news_app;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentAdapter extends FragmentPagerAdapter {
int count;
public FragmentAdapter(FragmentManager fm, int count) {
super(fm);
this.count = count;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 temp = new Fragment1();
return temp;
case 1:
Fragment2 temp2 = new Fragment2();
return temp2;
case 2:
Fragment3 temp3 = new Fragment3();
return temp3;
}
return null;
}
#Override
public int getCount() {
return count;
}
}
package com.josh_davey.news_app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment3 extends Fragment {
public Fragment3() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GetData getData = new GetData(getContext(),getActivity());
getData.execute("lincoln");
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment3, container, false);
}
}
If you need link to the full code it's on my github. Thanks in advance for any help
https://github.com/jdavey1996/News-Android-App
Default ViewPager's offscreenPageLimit is 1. So the tab3 is detached when tab1 is re-selected. If fragment is detached, Fragment's views are destroyed.
see: ViewPager.setOffscreenPageLimit
So I recommend you to set offscreenPageLimit to 2.
viewPager.setOffscreenPageLimit(2);
Or you can hold the list of ArticleConstructor in Fragment3 like blew.
GetData.java:
public class GetData extends AsyncTask<String, String,ArrayList<ArticleConstructor>>{
Callback callback;
interface Callback {
void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors);
}
public GetData(Callback callback) {
this.callback = callback;
}
...
#Override
protected void onPostExecute(ArrayList<ArticleConstructor> result) {
callback.onArticleConstructorLoaded(result);
}
....
}
Fragment3.java:
public class Fragment3 extends Fragment implements GetData.Callback {
private ListView listView;
private ArrayList<ArticleConstructor> articleConstructors = new ArrayList<>();
private ArticleArrayAdapter adapter;
public Fragment3() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment3, container, false);
listView = (ListView) view.findViewById(R.id.listView);
adapter = new ArticleArrayAdapter(getActivity(), getContext(), articleConstructors);
listView.setAdapter(adapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (articleConstructors.size() == 0) {
GetData getData = new GetData(this);
getData.execute("lincoln");
}
}
#Override
public void onArticleConstructorLoaded(ArrayList<ArticleConstructor> articleConstructors) {
this.articleConstructors = articleConstructors;
adapter.setArticleConstructors(articleConstructors);
}
}
I'm new beginner using Android studio I have currently watched a couple tutorials on setting up a basic swipe view which generates up to 3 all which replicate the original page known in my code as page_fragment_layout.xml. I want to take this a step further a be able to link different pages containing a range of content. In this case I want to be able to link my Activity_main.xml and page_fragment_layout.xml together by swipe. I have added my code so far I would be most appreciative of any input.
MainActivity.java
package socialdeveloper.swipecard;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager());
viewPager.setAdapter(swipeAdapter);
}
}
PageFragment.java
package socialdeveloper.swipecard;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class PageFragment extends android.support.v4.app.Fragment {
TextView textView;
public PageFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.page_fragment_layout,container,false);
textView = (TextView)view.findViewById(R.id.TestText);
Bundle bundle = getArguments();
String message = Integer.toString(bundle.getInt("count"));
textView.setText("This is the "+message+ "Swipe View Page...");
return view;
}
}
SwipeAdapter.java
package socialdeveloper.swipecard;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Hadleigh on 07/12/2015.
*/
public class SwipeAdapter extends FragmentStatePagerAdapter {
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle bundle = new Bundle();
int i = 0;
bundle.putInt("count",i+1);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
in your SwipeAdapter.java use this
` public Fragment getItem(int position) {
Fragment fragment = null;//Creates a fragment variable to hold the fragment class i create and make it a null so i can catch the error
if (position == 0) {
fragment = new PUT_THE_TITLE_OF_YOUR_ACTIVITY_YOU_WANT_TO_USE();//Calls the fragment.
}
if (position == 1) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment;
}
if (position == 2) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment.
}
return fragment;
}`
in the getItem() method to call other fragments or activities.