I am using for my Android app PagerSlidingTabStrip and Material Navigation Drawer libraries. I am watching strange behavior of ViewPager - when I am opening it first time, it works normally, but I am opening it again, ViewPager is empty, as without adapter.
MainActivity:
public class MainActivity extends AppCompatActivity {
private Drawer drawer;
private int lastSelection;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private boolean isClickedByUser = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = new DrawerBuilder().withActivity(MainActivity.this)
.withToolbar(toolbar).addDrawerItems(
new PrimaryDrawerItem().withName(R.string.name1)
.withIcon(R.drawable.icon1),
new PrimaryDrawerItem()
.withName(R.string.name2)
.withIcon(R.drawable.icon2))
.withOnDrawerItemClickListener(
new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(AdapterView<?> adapterView, View view,
int position, long id,
IDrawerItem iDrawerItem) {
switch (position) {
case 0:
setTitle(R.string.title1);
break;
case 1:
setTitle(R.string.title2);
break;
}
FragmentManager fManager = getSupportFragmentManager();
FragmentTransaction transaction = fManager.beginTransaction();
transaction.replace(R.id.container, PlaceholderFragment.newInstance(
position)).commitAllowingStateLoss();
lastSelection = position;
return false;
}
})
.build();
drawer.setSelection(0);
}
#Override
public void onBackPressed() {
if (drawer != null && drawer.isDrawerOpen()) {
drawer.closeDrawer();
} else {
super.onBackPressed();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
drawer.setSelection(lastSelection);
}
}
PlaceholderFragment, in that ViewPager is done:
public class PlaceholderFragment extends Fragment {
private static final String ID = "id";
private int id;
public static PlaceholderFragment newInstance(int id) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
switch (id) {
case 0:
rootView = inflater.inflate(R.layout.view1, container, false);
break;
case 1:
rootView = inflater.inflate(R.layout.tabs, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.viewPager);
pager.setAdapter(new PagerAdapter(getActivity().getSupportFragmentManager()));
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setShouldExpand(true);
tabs.setIndicatorColorResource(R.color.tab_indicator_color);
tabs.setTextColorResource(R.color.tab_text_color);
break;
default:
break;
}
return rootView;
}
private class PagerAdapter extends FragmentPagerAdapter {
private int[] titlesResIds = { R.string.title1, R.string.title2 };
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return getString(titlesResIds[position]);
}
#Override
public int getCount() {
return titlesResIds.length;
}
#Override
public Fragment getItem(int position) {
return TabFragment.newInstance(position);
}
}
}
TabFragment:
public class TabFragment extends ListFragment {
private static final String ID = "id";
private int id;
public static TabFragment newInstance(int id) {
TabFragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(ID, id);
fragment.setArguments(args);
return fragment;
}
public TabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://host/")
.build();
String result = null;
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(response));
reader.setLenient(true);
ArrayList<Message> messages = gson.fromJson(reader,
new TypeToken<ArrayList<Message>>(){}.getType());
int i = messages.size() - 1;
while (i != -1) {
if (messages.get(i).getType() != id)
messages.remove(i);
i--;
}
ArrayAdapter adapter = new MyListAdapter(messages);
setListAdapter(adapter);
}
};
asyncTask.execute();
return inflater.inflate(R.layout.fragment, container, false);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent messageIntent = new Intent(getActivity(), MessageActivity.class);
startActivity(messageIntent);
}
private class MyListAdapter extends ArrayAdapter {
private Context context = getActivity();
private ArrayList<Message> messages;
public MyListAdapter(ArrayList<Message> messages) {
super(getActivity(), R.layout.list_adapter);
this.messages = messages;
}
#Override
public int getCount() {
return messages.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_adapter, parent, false);
holder = new ViewHolder();
holder.imageIcon = (ImageView) convertView.findViewById(R.id.list_icon);
holder.textDatetime = (TextView) convertView.findViewById(R.id.list_text_datetime);
holder.textPrimary = (TextView) convertView.findViewById(R.id.list_text_primary);
holder.textSecondary = (TextView) convertView.findViewById(R.id.list_text_secondary);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Message message = messages.get(position);
long timestamp = message.getTimestamp() * 1000;
Date date = new Date(timestamp);
String datetime = new SimpleDateFormat("dd.MM.yyyy hh:mm", Locale.US).format(date);
holder.imageIcon.setImageResource(message.getIcon() == 0 ?
R.drawable.icon1 :
R.drawable.icon2);
holder.textDatetime.setText(datetime);
holder.textPrimary.setText(message.getTitle());
holder.textSecondary.setText(message.getMessage());
return convertView;
}
private class ViewHolder {
ImageView imageIcon;
TextView textDatetime;
TextView textPrimary;
TextView textSecondary;
}
}
}
I already decided my problem. I'm insert method getChildFragmentManager() in my PlaceholderFragment as in this answer - How set ViewPager inside a Fragment.
Related
So i have a searchview placed in an activity which has a tablayout and viewpager.In the viewpager there is a fragment for each tab with a textview.What im trying to do is to get the input from the searchview and set the text of the textview with that input and i cant seem to be able to do it.I tried to put the input from the searchview in a bundle(this being done in the activity),and then get the arguments in the fragment in onCreateView() but the problem is that the activity and the fragment are being created simultaneously wthich means that the input from the searchview would be null.
This is the Activity:
public class SearchActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
SearchView searchView;
Toolbar toolbar;
ImageButton imageButtonBack;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
bindUI();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.AddFragment(new NewestFragment(), "Newest"); // this line can cause crashes
viewPagerAdapter.AddFragment(new OldestFragment(), "Oldest"); // this line can cause crashes
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
setSearchView();
setImageButtonBack();
}
private void setSearchView() {
searchView.requestFocus();
View v = searchView.findViewById(R.id.search_plate);
v.setBackgroundColor(Color.parseColor("#ffffff"));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
searchView.clearFocus();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Bundle bundle = new Bundle();
bundle.putString("searchViewText", searchView.getQuery().toString());
NewestFragment newestFragment = new NewestFragment();
OldestFragment oldestFragment = new OldestFragment();
newestFragment.setArguments(bundle);
oldestFragment.setArguments(bundle);
return false;
}
});
}
private void bindUI() {
imageButtonBack = findViewById(R.id.back);
tabLayout = findViewById(R.id.tabs);
viewPager = findViewById(R.id.view_pager);
searchView = findViewById(R.id.search_view_searchactivity);
toolbar = findViewById(R.id.toolbar_selected_category);
}
private void setImageButtonBack() {
imageButtonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
The adapter of the ViewPager:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>(); // this line can cause crashes
private final List<String> titlesList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fragmentManager) {
super(fragmentManager);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return titlesList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titlesList.get(position);
}
public void AddFragment(Fragment fragment, String title) {
fragmentList.add(fragment); // this line can cause crashes
titlesList.add(title);
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
And here is the fragment:
public class NewestFragment extends Fragment {
View view;
TextView textView;
public NewestFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_search_newest, container, false);
textView=view.findViewById(R.id.tttttttttttttttttttt);
try {
String searchViewText=getArguments().getString("searchViewText");
textView.setText(searchViewText);
}
catch (Exception e){
//something
}
return view;
}
}
The fragments are attached to activity so first activity is created lets leave that but I think you should use a MVVM pattern and create viewmodel and then you can observe the search view and update the fragment textview using that viewmodel class
https://codelabs.developers.google.com/codelabs/kotlin-android-training-live-data/index.html#0
To change the fragments that are created by a FragmentPagerAdapter, you should use a DynamicFragmentPagerAdapter. Refer to the following code below.
public class DynamicFragmentPagerAdapter extends PagerAdapter {
private static final String TAG = "DynamicFragmentPagerAdapter";
private final FragmentManager fragmentManager;
public static abstract class FragmentIdentifier implements Parcelable {
private final String fragmentTag;
private final Bundle args;
public FragmentIdentifier(#NonNull String fragmentTag, #Nullable Bundle args) {
this.fragmentTag = fragmentTag;
this.args = args;
}
protected FragmentIdentifier(Parcel in) {
fragmentTag = in.readString();
args = in.readBundle(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(fragmentTag);
dest.writeBundle(args);
}
protected final Fragment newFragment() {
Fragment fragment = createFragment();
Bundle oldArgs = fragment.getArguments();
Bundle newArgs = new Bundle();
if(oldArgs != null) {
newArgs.putAll(oldArgs);
}
if(args != null) {
newArgs.putAll(args);
}
fragment.setArguments(newArgs);
return fragment;
}
protected abstract Fragment createFragment();
}
private ArrayList<FragmentIdentifier> fragmentIdentifiers = new ArrayList<>();
private FragmentTransaction currentTransaction = null;
private Fragment currentPrimaryItem = null;
public DynamicFragmentPagerAdapter(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
private int findIndexIfAdded(FragmentIdentifier fragmentIdentifier) {
for (int i = 0, size = fragmentIdentifiers.size(); i < size; i++) {
FragmentIdentifier identifier = fragmentIdentifiers.get(i);
if (identifier.fragmentTag.equals(fragmentIdentifier.fragmentTag)) {
return i;
}
}
return -1;
}
public void addFragment(FragmentIdentifier fragmentIdentifier) {
if (findIndexIfAdded(fragmentIdentifier) < 0) {
fragmentIdentifiers.add(fragmentIdentifier);
notifyDataSetChanged();
}
}
public void removeFragment(FragmentIdentifier fragmentIdentifier) {
int index = findIndexIfAdded(fragmentIdentifier);
if (index >= 0) {
fragmentIdentifiers.remove(index);
notifyDataSetChanged();
}
}
#Override
public int getCount() {
return fragmentIdentifiers.size();
}
#Override
public void startUpdate(#NonNull ViewGroup container) {
if (container.getId() == View.NO_ID) {
throw new IllegalStateException("ViewPager with adapter " + this
+ " requires a view id");
}
}
#SuppressWarnings("ReferenceEquality")
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
final FragmentIdentifier fragmentIdentifier = fragmentIdentifiers.get(position);
// Do we already have this fragment?
final String name = fragmentIdentifier.fragmentTag;
Fragment fragment = fragmentManager.findFragmentByTag(name);
if (fragment != null) {
currentTransaction.attach(fragment);
} else {
fragment = fragmentIdentifier.newFragment();
currentTransaction.add(container.getId(), fragment, fragmentIdentifier.fragmentTag);
}
if (fragment != currentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
currentTransaction.detach((Fragment) object);
}
#SuppressWarnings("ReferenceEquality")
#Override
public void setPrimaryItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
Fragment fragment = (Fragment) object;
if (fragment != currentPrimaryItem) {
if (currentPrimaryItem != null) {
currentPrimaryItem.setMenuVisibility(false);
currentPrimaryItem.setUserVisibleHint(false);
}
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
currentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(#NonNull ViewGroup container) {
if (currentTransaction != null) {
currentTransaction.commitNowAllowingStateLoss();
currentTransaction = null;
}
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return ((Fragment) object).getView() == view;
}
#Override
public Parcelable saveState() {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("fragmentIdentifiers", fragmentIdentifiers);
return bundle;
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
Bundle bundle = ((Bundle)state);
bundle.setClassLoader(loader);
fragmentIdentifiers = bundle.getParcelableArrayList("fragmentIdentifiers");
}
}
Hi I am using Tablayout in my
TAB1 TAB2 TAB3
When I open the app, by default TAB1 is selected. All the TABs have recyclerview. Now I have one FAB button for all the fragments. I am using FAB button for changing language.
Whenever user change language data will display as per language selection. Now issue is When I am on TAB3 and changing language instead of staying on TAB3 it goes to TAB1.
Can any one help me to solve this issue.
public class LibraryFragment extends Fragment {
private static final String TAG = LibraryFragment.class.getSimpleName();
private TabLayout tabLayout;
private ViewPager viewPager;
private String catid;
private FragmentManager fragmentManager;
private String SELECTED_ACTION;
private String SELECTED_LANGUAGE,SELECTED_LANGUAGENM,sel_cat;
private int VID_CODE;
private FloatingActionButton fab;
private ArrayList<LanguageModel> langList;
public LibraryFragment() {
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_library, container, false);
langList = (ArrayList<LanguageModel>) getArguments().getSerializable("langlist");
catid = getArguments().getString("frommusic");
SELECTED_ACTION = getArguments().getString("action");
SELECTED_LANGUAGE = getArguments().getString("sel_lang");
SELECTED_LANGUAGENM = getArguments().getString("sel_langnm");
sel_cat = getArguments().getString("sel_cat");
System.out.println("in library" + SELECTED_LANGUAGE);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
viewPager = (ViewPager) view.findViewById(R.id.view_pager);
viewPager.setAdapter(new CustomFragmentPageAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
fab = (FloatingActionButton) view.findViewById(R.id.fabChat);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setdailog();
}
});
return view;
}
public void setdailog()
{
final Dialog cpDialog = new Dialog(getActivity());
cpDialog.setTitle("Select Language");
cpDialog.setContentView(R.layout.alert_list);
ListView listView = (ListView) cpDialog.findViewById(R.id.listiview_lang);
AlertListAdapter mAdapter = new AlertListAdapter(langList, getActivity());
listView.setAdapter(mAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SELECTED_LANGUAGE = langList.get(position).getLangid();
System.out.println("JO JO"+SELECTED_LANGUAGE);
Intent intent=new Intent(getActivity(),MusicActivity.class);
intent.putExtra("langlist",langList);
intent.putExtra("selid",catid);
intent.putExtra("langid",SELECTED_LANGUAGE);
intent.putExtra("langname",langList.get(position).getLangname());
intent.putExtra("selcat",sel_cat);
startActivity(intent);
cpDialog.dismiss();
}
});
cpDialog.show();
}
public class AlertListAdapter extends BaseAdapter {
ArrayList<LanguageModel> mData;
Context mContext;
LayoutInflater inflater;
public AlertListAdapter(ArrayList<LanguageModel> data, Context context) {
mData = data;
mContext = context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_alert_list, null);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.textView_languge);
tvTitle.setText(mData.get(position).getLangname());
return convertView;
}
}
public class CustomFragmentPageAdapter extends FragmentPagerAdapter {
private final String TAG = CustomFragmentPageAdapter.class.getSimpleName();
private static final int FRAGMENT_COUNT = 3;
public CustomFragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment f1 = new SongFragment();
Bundle args1 = new Bundle();
args1.putString("fromlibfrag", catid);
args1.putString("action", SELECTED_ACTION);
args1.putString("sel_lang", SELECTED_LANGUAGE);
args1.putSerializable("langlist",langList);
f1.setArguments(args1);
return f1;
case 1:
Fragment f2 = new PhotoFragment();
Bundle args2 = new Bundle();
args2.putString("fromlibfrag", catid);
args2.putString("action", SELECTED_ACTION);
args2.putString("sel_lang", SELECTED_LANGUAGE);
args2.putSerializable("langlist",langList);
f2.setArguments(args2);
return f2;
case 2:
Fragment f3 = new SmsFragment();
Bundle args3 = new Bundle();
args3.putString("fromlibfrag", catid);
args3.putString("action", SELECTED_ACTION);
args3.putString("sel_lang", SELECTED_LANGUAGE);
args3.putSerializable("langlist",langList);
f3.setArguments(args3);
return f3;
}
return null;
}
#Override
public int getCount() {
return FRAGMENT_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Videos";
case 1:
return "Photos";
case 2:
return "SMS";
}
return null;
}
}
}
int position=0;
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override public void onTabSelected(TabLayout.Tab tab){
position = tab.getPosition();
} });
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setdailog(position);
}
});
Now
public void setdailog(int currentTab)
{
final Dialog cpDialog = new Dialog(getActivity());
cpDialog.setTitle("Select Language");
cpDialog.setContentView(R.layout.alert_list);
ListView listView = (ListView) cpDialog.findViewById(R.id.listiview_lang);
AlertListAdapter mAdapter = new AlertListAdapter(langList, getActivity());
listView.setAdapter(mAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SELECTED_LANGUAGE = langList.get(position).getLangid();
System.out.println("JO JO"+SELECTED_LANGUAGE);
Intent intent=new Intent(getActivity(),MusicActivity.class);
intent.putExtra("langlist",langList);
intent.putExtra("selid",catid);
intent.putExtra("langid",SELECTED_LANGUAGE);
intent.putExtra("langname",langList.get(position).getLangname());
intent.putExtra("selcat",sel_cat);
intent.putExtra("currentTab" , currentTab);
startActivity(intent);
finish();
cpDialog.dismiss();
}
});
cpDialog.show();
}
Now In MusicActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int currentTab = intent.getIntExtra("currenttab", 0);
//here you can check if you get 1, 2 or 3 in currentTab then you have to set current tab to 1, 2 or 3 respectively.
}
so here is my problem, i have only one activity from i launch my viewpager fragment, in my viewpager i have 4 fragments containing recyclerViews. Every Fragment contains item populated by data on the net, when i click into one i get a WebView Fragment, but when i click on the backbutton i lost my poisiton, cause it's recreating the whole activity.
I don't know how to not recreate the activity and get back my old position, or recreating it but not changing the item's positions and have my old position back. Here's my code. Where i should put what ?! Some help would be very very well come.
Thank You !!
My Activity Class :
public class LauncherActivity extends AppCompatActivity implements ListFragment.OnNewSelectedInterface{
public static final String VIEWPAGER_FRAGMENT = "view_pager";
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_launcher);
mImageView = (ImageView) findViewById(R.id.logoImageView);
mImageView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_indefinitely));
if(!isNetworkAvailable()){
alertUserAboutError();
} else {
relativeLayout.postDelayed(new Runnable() {
#Override
public void run() {
ViewPagerFragment savedFragment = (ViewPagerFragment)
getSupportFragmentManager().findFragmentByTag(VIEWPAGER_FRAGMENT);
if(savedFragment == null) {
ViewPagerFragment viewPagerFragment = new ViewPagerFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activity_launcher, viewPagerFragment, VIEWPAGER_FRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
}, 2000);
}
}
#Override
public void onListNewSelected(int index, ArrayList<Articles> articles) {
WebViewFragment webViewFragment = new WebViewFragment();
Bundle bundle = new Bundle();
bundle.putInt(ViewPagerFragment.KEY_NEW_INDEX, index);
bundle.putParcelableArrayList(ListFragment.KEY_LIST, articles);
webViewFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getFragmentManager(), "error_dialog");
}
}
My ViewPagerClass :
public class ViewPagerFragment extends Fragment {
public static final String KEY_NEW_INDEX = "key_new_index";
private ViewPager mViewPager;
private TabLayout mTabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
final OldFactFragment oldFactFragment = new OldFactFragment();
final SportFragment sportFragment = new SportFragment();
final BuzzFragment buzzFragment = new BuzzFragment();
final NewsFragment newsFragment = new NewsFragment();
mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mTabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
if(position == 0){
return oldFactFragment;
} else if (position == 1) {
return newsFragment;
} else if (position == 2){
return sportFragment;
} else return buzzFragment;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Pastly";
} else if (position == 1) {
return "politic";
} else if (position == 2){
return "sport";
} else return "buzz";
}
#Override
public int getCount() {
return 4;
}
});
mTabLayout.setupWithViewPager(mViewPager);
return view;
}
}
My ListFragment(Parent's class of the 4 Fragments in the ViewPager) :
public abstract class ListFragment extends Fragment {
public static final String KEY_LIST = "key_list";
public interface OnNewSelectedInterface {
void onListNewSelected(int index, ArrayList<Articles> articles);
}
protected static final String TAG = ListFragment.class.getSimpleName();
protected ArrayList<Articles> mArticlesList;
protected ItemAdapter mArticleAdapter;
protected RecyclerView mRecyclerView;
protected OnNewSelectedInterface mListener;
protected RecyclerView.LayoutManager mManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mListener = (OnNewSelectedInterface) getActivity();
View view = inflater.inflate(R.layout.fragment_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
getInfos(getUrl());
return view;
}
protected abstract String[] getUrl();
private void getInfos(String[] url) {
if (isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
for (int i = 0; i < getUrl().length; i++) {
Request request = new Request.Builder().url(url[i]).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
Log.v(TAG, jsonData);
getMultipleUrls(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getCurrentArticles(mArticlesList);
}
});
} else {
alertUserAboutError();
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
alertUserAboutError();
}
});
}
});
}
} else{
alertUserAboutError();
}
}
private void getMultipleUrls(String jsonData) throws JSONException {
if (mArticlesList == null) {
mArticlesList = getArticleForecast(jsonData);
} else {
mArticlesList.addAll(getArticleForecast(jsonData));
}
}
private void getCurrentArticles(ArrayList<Articles> articles) {
mArticleAdapter = new ItemAdapter(getActivity(), articles, mListener);
mRecyclerView.setAdapter(mArticleAdapter);
mManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mManager);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getActivity().getFragmentManager(), "error_dialog");
}
private ArrayList<Articles> getArticleForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray articles = forecast.getJSONArray("articles");
ArrayList<Articles> listArticles = new ArrayList<>(articles.length());
for (int i = 0; i < articles.length(); i++) {
JSONObject jsonArticle = articles.getJSONObject(i);
Articles article = new Articles();
String urlImage = jsonArticle.getString("urlToImage");
article.setTitle(jsonArticle.getString("title"));
article.setDescription(jsonArticle.getString("description"));
article.setImageView(urlImage);
article.setArticleUrl(jsonArticle.getString("url"));
listArticles.add(i, article);
}
return listArticles;
}
}
And my ItemAdapter (Adapter Class) :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ArticleViewHolder> {
private final ListFragment.OnNewSelectedInterface mListener;
protected ArrayList<Articles> mArticlesList;
protected Context mContext;
private int mPosition;
private int lastPosition = -1;
public ItemAdapter(Context contexts, ArrayList<Articles> mArticleLi, ListFragment.OnNewSelectedInterface listener){
mContext = contexts;
mArticlesList = mArticleLi;
mListener = listener;
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_linear, parent, false);
view.findViewById(R.id.textView).setSelected(true);
ArticleViewHolder articleViewHolder = new ArticleViewHolder(view);
articleViewHolder.setIsRecyclable(false);
return articleViewHolder;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(ArticleViewHolder holder, int position) {
mPosition = position;
holder.bindArticle(mArticlesList.get(position));
setAnimation(holder.itemView, position);
holder.mImageView.setClipToOutline(true);
}
private void setAnimation(View viewToAnimate, int position) {
if (position > lastPosition) {
Animation animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public int getItemCount() {
return mArticlesList.size();
}
public class ArticleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
private TextView mTitle, mArticle;
private ImageView mImageView;
private ArticleViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.textView);
mArticle = (TextView) itemView.findViewById(R.id.showTextView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView2);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
private void bindArticle(Articles article) {
mTitle.setText(article.getTitle());
mArticle.setText(article.getDescription());
mArticle.setVisibility(View.INVISIBLE);
Glide.with(mContext).load(article.getImageView()).into(mImageView);
}
#Override
public void onClick(View view) {
mListener.onListNewSelected(getLayoutPosition(), mArticlesList);
}
#Override
public boolean onLongClick(View view) {
String desc = mArticlesList.get(getAdapterPosition()).getDescription();
mArticle.setVisibility(View.VISIBLE);
mArticle.setText(desc);
mArticle.postDelayed(new Runnable() {
public void run() {
mArticle.setVisibility(View.INVISIBLE);
}
}, 3000);
return true;
}
}
}
In Your method onListNewSelected You are Replacing the new fragment with the old one as stated in this line
fragmentTransaction.replace(R.id.activity_launcher, webViewFragment, WebViewFragment.WEBVIEWFRAGMENT);
From Google Documentaion
Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
So you are removing the old Fragment then adding the new one, When you are back to get the old fragment, It is not already there it will be created from scratch, So the position is already gone with the removed fragment.
While using the add method, Will add the new fragment above the previous one, when you go back the previous one already there with its state "Position"
in my App i have Gridview and TabActivity.
my Rice.class has gridview,
in MainActivity.class has tabActivity ,
myChild Tabs are FragmentA,FragmentB,FragmnetC.
i want pass my gridview index to FragmnetA.how can i slove this problem.
Rice.class
public class Rice extends ActionBarActivity {
FragmentA fa;
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rice);
gridView=(GridView) findViewById(R.id.gridViewR);
gridView.setAdapter(new MyRAdapter(this));
Intent intent = getIntent();
//Breakfast bf = (Breakfast) getFragmentManager().findFragmentById(R.id.fragment2);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("index",i);
startActivity(intent);
}
});
}
}
class MyRAdapter extends BaseAdapter {
private Context mContext;
public MyRAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
//imageView.setLayoutParams(new GridView.LayoutParams(450, 200));
//imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
private Integer[] mThumbIds = {
R.drawable.back_1, R.drawable.back_2,
R.drawable.back_3, R.drawable.back_4,
R.drawable.back_5, R.drawable.back_6,
R.drawable.back_11,
};
}
MainActivity.class
public class MainActivity extends FragmentActivity {
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyFrAdapter(fragmentManager));
Intent intent = getIntent();
int index = intent.getIntExtra("index",0);
}
}
class MyFrAdapter extends FragmentPagerAdapter{
public MyFrAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if(i==0){
fragment = new FragmentA();
}
if(i==1){
fragment = new FragmentB();
}
if(i==2){
fragment = new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Ingredient";
}
if(position == 1){
return "Recipe";
}
if(position == 2){
return "Summary";
}
return null;
}
}
FragmentA.class
public class FragmentA extends Fragment {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a,container,false);
textView = (TextView) view.findViewById(R.id.textView);
return view;
}
}
public class MainActivity extends FragmentActivity {
int mIndex;
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyFrAdapter(fragmentManager));
Intent intent = getIntent();
mIndex = intent.getIntExtra("index",0);
}
class MyFrAdapter extends FragmentPagerAdapter{
public MyFrAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if(i==0){
fragment = new FragmentA().newInstance(mIndex);
}
if(i==1){
fragment = new FragmentB();
}
if(i==2){
fragment = new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Ingredient";
}
if(position == 1){
return "Recipe";
}
if(position == 2){
return "Summary";
}
return null;
}
}
}
//...
public class FragmentA extends Fragment {
TextView textView;
int FragmentA_index;
public static final String EXTRA_INDEX = "mypackage.index";
public static FragmentA newInstance(int index) {
Bundle args = new Bundle();
args.putInt(EXTRA_INDEX, index);
FragmentA fragment = new FragmentA();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentA_index = getArguments().getInt(EXTRA_INDEX);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a,container,false);
textView = (TextView) view.findViewById(R.id.textView);
return view;
}
}
Could be this is a dupe, but I've been looking for solutions and they always slightly differ from my problem.
So:
I'm currently creating an app that has 2 fragments that are swipeable. TaskGroupFragment shows a list and when you click on an item it wil slide to TasksFragment and show you a sublist. What I have to do now is send the id of the selected item from groups to tasks so I can get the sublist out of SQLite.
I know I'm supposed to communicate through the connected MainActivity and I'm already at the point that I've created an interface in TaskGroupsFragment and implemented this in the activity. Tried and tested and the activity receives the TaskGroupID.
The part where I'm stuck is getting this info in TasksFragment. Especially using swipeview makes this harder.
My code:
MainPagerAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
case 1: return TasksFragment.newInstance();
default: return TaskGroupFragment.newInstance();
}
}
#Override
public int getCount() {
return 2;
}
}
TaskGroupActivity (sending fragment):
public class TaskGroupFragment extends ListFragment {
private DoItDataSource dataSource;
private List<TaskGroups> groups;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_group, container, false);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
JSONContainer jsonContainer = dataSource.sqliteToContainer();
dataSource.close();
groups = jsonContainer.getTask_groups();
TaskGroupAdapter adapter = new TaskGroupAdapter(getActivity(), groups);
setListAdapter(adapter);
return view;
}
public static TaskGroupFragment newInstance() {
TaskGroupFragment tgf = new TaskGroupFragment();
return tgf;
}
public interface OnTaskGroupSelectedListener {
public void onTaskGroupSelected(String taskGroupId);
}
OnTaskGroupSelectedListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnTaskGroupSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " Interface not implemented in activity");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity)getActivity()).setCurrentItem(1, true);
mListener.onTaskGroupSelected(groups.get(position).getId());
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
pager = (ViewPager) findViewById(R.id.activity_main_pager);
pager.setAdapter(new MainPagerAdapter(getSupportFragmentManager()));
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// getting lists
//
}
private void resultHandling(String json, String day) {
if (day.equals("today")) {
Gson gson = new Gson();
containerToday = gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerToday, "Today");
} else if (day.equals("tomorrow")) {
Gson gson = new Gson();
containerTomorrow= gson.fromJson(json, JSONContainer.class);
jsonToSQLite(containerTomorrow, "Tomorrow");
}
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// Enter missing link here?
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment
implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button)
view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
dataSource.open();
tasks = dataSource.getTasks("204"); // 204 is a placeholder, TaskGroupId should be here
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
public static TasksFragment newInstance() {
TasksFragment tif = new TasksFragment();
return tif;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Solution
Thanks to Alireza! I had to make several changes to his proposed code, but in the end it helped me in finding the solution!
MainPageAdapter:
public class MainPagerAdapter extends FragmentStatePagerAdapter {
// ADDED
private String taskGroupId;
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0: return TaskGroupFragment.newInstance();
// MODIFIED
case 1:
Bundle args = new Bundle();
logcat("before setBundle " + taskGroupId);
args.putString("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
default: return TaskGroupFragment.newInstance();
}
}
// ADDED
public void setTaskGroupId(String id){
this.taskGroupId = id;
}
#Override
public int getCount() {
return 2;
}
}
MainActivity:
public class MainActivity extends FragmentActivity implements
TaskGroupFragment.OnTaskGroupSelectedListener{
private SharedPreferences savedValues;
private DoItDataSource dataSource = new DoItDataSource(this);
private String identifier, user, domain;
private JSONContainer containerToday;
private JSONContainer containerTomorrow;
// ADDED
private MainPagerAdapter adapter;
public ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedValues = getSharedPreferences("SavedValues", MODE_PRIVATE);
identifier = savedValues.getString("Identifier", "");
// ADDED
adapter = new MainPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.activity_main_pager);
// MODIFIED
pager.setAdapter(adapter);
if (identifier == null || identifier.equals("")) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("APP_ID", APP_ID);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
identifier = savedValues.getString("Identifier", "");
user = savedValues.getString("User", "");
domain = savedValues.getString("Domain", "");
boolean onBackPressed = savedValues.getBoolean("OnBackPressed", false);
//
// Getting lists
//
}
String taskGroupId = "";
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
// ADDED
adapter.setTaskGroupId(taskGroupId);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
}
TaskFragment (receiving fragment):
public class TasksFragment extends ListFragment implements OnClickListener {
private final static String TAG = "TaskItemFragment logging";
private DoItDataSource dataSource;
private List<Tasks> tasks;
private String taskGroupId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_item, container, false);
Button backButton = (Button) view.findViewById(R.id.fragment_task_item_bar_back_button);
dataSource = new DoItDataSource(getActivity());
// ADDED
Bundle bundle = getArguments();
taskGroupId = bundle.getString("taskGroupId");
// MODIFIED
dataSource.open();
tasks = dataSource.getTasks(taskGroupId);
dataSource.close();
TasksAdapter adapter = new TasksAdapter(getActivity(), tasks);
setListAdapter(adapter);
backButton.setOnClickListener(this);
return view;
}
// CAN BE REMOVED?
//public static TasksFragment newInstance() {
// TasksFragment tif = new TasksFragment();
// return tif;
//}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "Clicked item " + position, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fragment_task_item_bar_back_button:
((MainActivity)getActivity()).setCurrentItem(0, true);
break;
}
}
}
Please note that I'm using taskGroupId as a String, not an int.
First you need to make sure your adapter knows about taskGroupID. just add a variable and a public method to your adapter.
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private int taskGroupId;
public void setTaskGroupId(int id){
this.taskGroupId = id;
}
}
then store a reference to your adapter in your activity. Now simply call this method whenever GroupId changes
#Override
public void onTaskGroupSelected(String taskGroupId) {
this.taskGroupId = taskGroupId;
adapter.setTastGroupId = taskGroupId; //data needed to initialize fragment.
adapter.setCurrentItem(1); //going to TasksFragment page
}
then you need to put some argumants before starting your fragment.
#Override
public Fragment getItem(int i) {
//this code is only for case 1:
Bundle args = new Bundle();
args.putInt("taskGroupId",taskGroupId);
Fragment fragment = new TasksFragment();
fragment.setArguments(args);
return fragment;
}
and lastly use this data in your TaskFragment to show the right content.