Currently, the project in question is set up using a ViewPager which has an adapter capable of loading 4 different fragments. The last 3 Fragments are dependent upon the first fragment giving them a value (the SQL foreign key comes from the a value from the first item in the ViewPager).
My question is: how do I retrieve a value from the first Fragment's EditText, perform an SQL Operation and pass a value once the user attempts to "swipe" to the next tab?
Note, that I am trying to do this on swipe, and not via button. So far I have attempted to override OnPageScrolled, which yielded a null pointer when referring to the first fragment. I am assuming that the first fragment has been destroyed when I attempt to call it's hasPopulatedClassName() function
For Reference, the offending activity. Note the comment under OnPageScrolled
public class ActivityClassEdit extends FragmentActivity implements ViewPager.
private ClassEditPagerAdapter aPager;
//Views
private ViewPager vPager;
//Boolean telling us if we are good to move on to Criteria, People, or Links
private boolean mClassInserted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_edit);
if(getIntent().hasExtra(CM.BKEY_PASSED_SEMESTERKEY)){
//Set the views
vPager=(ViewPager) findViewById(R.id.ace_pager);
//Instantiate the pager and set it
aPager=new ClassEditPagerAdapter(this, getIntent().getExtras().getLong(CM.BKEY_PASSED_SEMESTERKEY, -1));
vPager.setAdapter(aPager);
vPager.setOnPageChangeListener(this);
} else {
//TODO handle not having a semester key
}
}
//=============PageScrollListener==============
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(!mClassInserted) {
if (position == 1) {
//FragmentClassEdit fCE = (FragmentClassEdit) aPager.getRegisteredFragment(0);
FragmentClassEdit fCE = (FragmentClassEdit) aPager.getRegisteredFragment(0);
if (fCE.hasPopulatedClassName() == false) {
vPager.setCurrentItem(0);
Toast.makeText(this, getResources().getString(R.string.toast_typeInClassName), Toast.LENGTH_LONG).show();
} else {
//Save to shared Preferences, in case we have to delete on user cancellation
//null pointer here!!!
long mInsertedClassID= Long.getLong(fCE.insertClass());
getSharedPreferences(CM.SP, Activity.MODE_PRIVATE).edit().putLong(CM.SP_LASTINSERTEDCLASS, mInsertedClassID).apply();
aPager.setClassID(mInsertedClassID);
vPager.setCurrentItem(position);
}
}
} else {
vPager.setCurrentItem(position);
}
}
And here is the ViewPagerAdapter:
public class ClassEditPagerAdapter extends FragmentStatePagerAdapter{
private FragmentClassEdit fCE;
private Fragment fCrit;
private Fragment fLinks;
private Fragment fPeople;
private FragmentManager fragmentManager;
private String[] sTabText;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
private Context ctx;
private long semID;
private long cID;
public ClassEditPagerAdapter(FragmentActivity context, long semesterID){
super(context.getSupportFragmentManager());
fragmentManager=context.getSupportFragmentManager();
ctx= context;
sTabText = ctx.getResources().getStringArray(R.array.cepa_titles);
cID=-1;
semID=semesterID;
}
public void setClassID(long classID){
cID=classID;
}
#Override
public Fragment getItem(int fragID) {
switch (fragID) {
//FragClassEdit
case 0:
fCE = FragmentClassEdit.newInstance(semID);
return fCE;
//FragTypeEdit
case 1:
fCrit = FragmentCriteriaEdit.newInstance(cID);
return fCrit;
//FragPeople
case 2:
fPeople = FragmentPeopleEdit.newInstance(cID);
return fPeople;
//FragLinks
case 3:
fLinks = FragmentLinkEdit.newInstance(cID);
return fLinks;
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
#Override
public int getCount() {
return 4;
}
#Override
public String getPageTitle(int position){
return sTabText[position];
}
}
Related
I have a TreeTableView which allows multiselection. I got a ContextMenu for editing or deleting that selected items.
Delete and edit should only be enabled if there is at least one selection.
final BooleanBinding isTableSelectionEmpty = Bindings.isEmpty(this.table.getSelectionModel().getSelectedItems());
this.menuItemDelete.disableProperty().bind(isTableSelectionEmpty);
That is working as expected.
But now I have dependencies on different values of the selected rows. Like for example that the row is system-mandatory and should not be deleted.
I tried the following but it is not working
final BooleanBinding invalidSelection = Bindings.and(Bindings.isEmpty(tableSelection),
Bindings.isNotEmpty(tableSelection.filtered(item -> {
this.logger.trace("filtering :" + item);
return item.getValue().getSystemProperty().get();
})));
this.menuItemDelete.disableProperty().bind(invalidSelection);
Not even the debug-trace is printed and the value of the binding is always false (thus enabling the menu item). Now I am a bit lost. Where is my mistake?
FilteredList relies on a correct ListIterator, but currently there is a bug in the ListIterator the selectedItems list in MultipleSelectionModelBase. This prevents the filtering to properly work. To fix this you could create a ObservableList implementation delegating everything but the ListIterator creation to a source ObservableList. Most IDEs have a functionality to generate this kind of methods automatically, reducing the amount of work to a minimum (e.g.in NetBeans: Generate -> Delegate Method).
public class ObservableListIteratorFix<T> implements ObservableList<T> {
private final ObservableList<T> list;
public ObservableListIteratorFix(ObservableList<T> list) {
this.list = list;
}
#Override
public void addListener(ListChangeListener<? super T> listener) {
list.addListener(listener);
}
#Override
public void removeListener(ListChangeListener<? super T> listener) {
list.removeListener(listener);
}
#Override
public boolean addAll(T... elements) {
return list.addAll(elements);
}
...
private class CustomListIterator implements ListIterator<T> {
private final ListIterator<T> iterator;
private int index;
public CustomListIterator(int index) {
this.iterator = list.listIterator(index);
this.index = index;
}
#Override
public boolean hasNext() {
return iterator.hasNext();
}
#Override
public T next() {
T t = iterator.next();
index++;
return t;
}
#Override
public boolean hasPrevious() {
return iterator.hasPrevious();
}
#Override
public T previous() {
T t = iterator.previous();
index--;
return t;
}
#Override
public int nextIndex() {
return index;
}
#Override
public int previousIndex() {
return index-1;
}
#Override
public void remove() {
iterator.remove();
}
#Override
public void set(T e) {
iterator.set(e);
}
#Override
public void add(T e) {
iterator.add(e);
}
#Override
public void forEachRemaining(Consumer<? super T> action) {
iterator.forEachRemaining(action);
}
}
#Override
public ListIterator<T> listIterator() {
return listIterator(0);
}
#Override
public ListIterator<T> listIterator(int index) {
return new CustomListIterator(index);
}
#Override
public FilteredList<T> filtered(Predicate<T> predicate) {
return new FilteredList<>(this, predicate);
}
...
This allows you to use the class as wrapper the selectedItems which should fix the filtering...
new ObservableListIteratorFix<>(tableSelection).filtered(...)
I am new in android using fragments in my Project. first time my fragment is creating then api called and get data load in fragment. here when i clicked at any item i replaced fragment by another fragment there also another api called and load data to fragment.
now here problem situation generated for me.
from here i back Button pressed.
fragment reloading same as first time creating but it should be show data as i left before going to next fragment.
so please provide me solution how i can get same data as i left means savedInstanceState data.
im my first fragment getCategory method call Api and get Data first time when i choose any category i replace fragment with another fragment but when i m returning same getCategory method recall perform same process as it first time.
fragment should not call api method again on backpressed it should show same category on this i clicked before.
my first fragment where calling api......
public class LandingFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GridLayoutManager gridLayoutManager;
private static RecyclerView category_Grid;
private Fragment myFragment = null;
ProgressBar mProgressView;
View mLoginFormView;
private Category category;
private CategoryAdapter categoryAdapter;
private List<CategoryObject> rowListItem;
private String productId;
private OnFragmentInteractionListener mListener;
public LandingFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LandingFragment.
*/
// TODO: Rename and change types and number of parameters
public static LandingFragment newInstance(String param1, String param2) {
LandingFragment fragment = new LandingFragment();
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);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_landing, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
RecyclerViewListeners();
}
// 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(Activity 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;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void initViews(final View v) {
mLoginFormView = (View)v.findViewById(R.id.mainView);
mProgressView = (ProgressBar)v.findViewById(R.id.login_progress);
category_Grid = (RecyclerView)v.findViewById(R.id.cat_grid);
category_Grid.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 3);
category_Grid.setLayoutManager(gridLayoutManager);
}
private void RecyclerViewListeners(){
category_Grid.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), category_Grid, new ItemClickListener(){
#Override
public void onClick(View view, int position) {
String entityId = rowListItem.get(position).getCategoryId();
String catName = rowListItem.get(position).getName();
Integer ishave = rowListItem.get(position).getIshaveSubcategories();
if(ishave==1) {
myFragment = SubcategoryFragment.newInstance(""+catName, "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}else{
myFragment = ProductListFragment.newInstance("", "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void getCategory() {
showProgress(true);
String URL = getResources().getString(R.string.category_api);
StringRequest req = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
Gson gson = new GsonBuilder().serializeNulls().create();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals(getResources().getString(R.string.response_success))){
category = gson.fromJson(response, Category.class);
rowListItem = category.getCategory();
if(navigationUpdated){
someEventListener.someEvent(rowListItem);
navigationUpdated = false;
}
Log.d("CATEGORYID::::::::",""+rowListItem.get(1).getCategoryId());
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
return;
}
else if (jsonObject.getString("status").equals(getResources().getString(R.string.login_Er_respose))){
Log.e("","ERRORRRRRR");
return;
}
} catch (JSONException e) {
showProgress(false);
Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(req);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
You can check your rowListItem.size(), if it's size is 0 then call getCategory() service, otherwise load your data from your rowListItem. Here is sample code which I am using to load data from arraylist if it is not empty:
if (mArrayArticle.size() == 0) {
isDataLoading = true;
mRecyclerList.setVisibility(View.INVISIBLE);
getCategory();
} else {
mHomeItemAdapter = new HomeItemAdapter(getActivity(), mArrayArticle, this);
mRecyclerList.setAdapter(mHomeItemAdapter);
}
Here mArrayArticle is my ArrayList, Hope it will help you.
for more clarification i want to tell..
how i implement the #Bhvk_AndroidBee solution
fragment backpressed call onActivityCreated Method so first overridethis method in fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//here you can check null condition for rowListItem
}
}
inside onActivityCreated method I checked the condition like that
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(rowListItem!=null){
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
}else {
//call the method for first time creating your view
getCategory();
}
}
hope this would be helpfull for more strugglers like me...
I need to order the list of items based on a field say starredAt
I am loading the data in the recyclerview from Realm DB using RealmRecyclerView by thorbenprimke
The field changes it value on user's action i.e when user presses star button the item should be moved to top.
For this I am just updating the starredAt field of the object.
The items are already sorted by starredAt so realm loads the updated list but it randomly adds one more item to the recyclerview.
CheatSheet.java
public class CheatSheet extends RealmObject {
#PrimaryKey
private String id;
private RealmList<Item> items;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public RealmList<Item> getItems() {
return items;
}
public void setItems(RealmList<Item> items) {
this.items = items;
}
}
Item.java
public class Item extends RealmObject {
#PrimaryKey
private String id;
private String description;
private Date starredAt;
public Item() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getStarredAt() {
return starredAt;
}
public void setStarredAt(Date starredAt) {
this.starredAt = starredAt;
}
}
CheatSheetActivity.java
public class MainActivity extends AppCompatActivity {
RealmRecyclerView revItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setData();
}
private void setData() {
rvItems = (RealmRecyclerView) findViewById(R.id.rev_items);
RealmResults<Item> items = Realm.getDefaultInstance().where(CheatSheet.class)
.equalTo("id", "some-id").findFirst().getItems()
.where()
.findAllSorted("starredAt", Sort.DESCENDING);
ItemRealmListAdapter itemRealmListAdapter =
new ItemRealmListAdapter(this, items,
true, true);
rvItems.setAdapter(itemRealmListAdapter);
}
ItemRealmListAdapter.java
public class ItemRealmListAdapter extends RealmBasedRecyclerViewAdapter<Item,
ItemRealmListAdapter.ItemViewHolder> {
RealmResults<Item> mItems;
public ItemRealmListAdapter(Context context, RealmResults<Item> realmResults,
boolean automaticUpdate, boolean animateResults) {
super(context, realmResults, automaticUpdate, animateResults);
this.mItems = realmResults;
}
#Override
public ItemViewHolder onCreateRealmViewHolder(ViewGroup viewGroup, int i) {
return new ItemViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_layout_cs_text, viewGroup, false));
}
public Item getItem(int position) {
return mItems.get(position);
}
#Override
public void onBindRealmViewHolder(ItemViewHolder itemViewHolder, int position) {
itemViewHolder.txtBody.setText(getItem(position).getDescription());
if (getItem(position).getStarredAt() != null) {
itemViewHolder.imvStar.setImageResource(R.drawable.ic_star_yellow);
}
itemViewHolder.imvStar.setOnClickListener(v -> handleStarClick(v,position));
}
private void handleStarClick(View v, int position) {
if (getItem(position).getStarredAt() != null) {
((ImageView) v).setImageResource(R.drawable.ic_star);
CheatSheetStorage.unStarItem("some-id", getItem(position));
} else {
((ImageView) v).setImageResource(R.drawable.ic_star_yellow);
CheatSheetStorage.starItem("some-id", getItem(position));
}
}
public static class ItemViewHolder extends RealmViewHolder {
#Bind(R.id.txt_cheat_sheet)
TextView txtBody;
#Bind(R.id.img_star)
ImageView imvStar;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
CheatSheetStorage.java
public class CheatSheetStorage {
public static void unStarItem(String cheatSheetId, Item item) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CheatSheet cheatSheet = getCheatSheetById(cheatSheetId);
Item itemDB = cheatSheet.getItems().where().equalTo("id", item.getId()).findFirst();
itemDB.setStarredAt(null);
realm.commitTransaction();
}
public static void starItem(String cheatSheetId, Item item) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
CheatSheet cheatSheet = getCheatSheetById(cheatSheetId);
Item itemDB = cheatSheet.getItems().where().equalTo("id", item.getId()).findFirst();
itemDB.setStarredAt(new Date());
realm.commitTransaction();
}
}
Please refer following screenshots for clearer idea :
Screenshot before starring
Screenshot after starring the sixth item
#Rohan-Peshkar - You will have to provide a animateExtraColumnName value to the adapter. For the animations, the adapter keeps track of the items and since that item's id doesn't change, the list isn't updated. With an additional column (in your case that should be the starredAt column - as long as it is stored as an Integer), the diffing algorithm will detect a change and the order is updated.
For reference: https://github.com/thorbenprimke/realm-recyclerview/blob/2835a543dce20993d8f98a4f773fa0e67132ce52/library/src/main/java/io/realm/RealmBasedRecyclerViewAdapter.java#L177
You can also check out the MainActivity in the example folder. The example changes a row's text from "ABC" to "Updated ABC" and the list recognizes the change because both the primary key and the quote field are used to basically create a composite key for diffing purposes.
I am trying to launch an activity from a recyclerview's item using OnClick method. I made an interface and used getAdapterPostion in the adapter. But the Activity is not launching. Here's my code:
Interface that I created in my Adapter:
public interface Clicklistener{
public void itemClicked(View view,int position);
}
}
Setter method for ClickListener:
public void setclickListener(Clicklistener clickListener){
this.clickListener = clickListener;
}
View Holder Method where I set the OnClickListener:
public class ViewHolderListMovies extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView movieThumbnail;
private TextView movieTitle;
private TextView movieYear;
public ViewHolderListMovies(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
movieThumbnail = (ImageView) itemView.findViewById(R.id.video_poster);
movieTitle = (TextView) itemView.findViewById(R.id.video_name);
movieYear = (TextView) itemView.findViewById(R.id.video_year);
}
#Override
public void onClick(View v) {
if(clickListener!=null){
clickListener.itemClicked(v,getAdapterPosition());
}
}
The I Initialised the the interface in the fragment:
listMoviesAdapter.setclickListener(this);
At last I started an intent in in the fragment to call the needed Activity:
#Override
public void itemClicked(View view, int position) {
startActivity(new Intent(getActivity(),MovieDetailsActivity.class));
}
Any Help is appreciated. Thanks!
Initialise the setoncliklistener in method onBindViewHolder. Example, may be help
public class HistoryAdapter extends RecyclerView.Adapter<HistoryAdapter.ViewHolder> {
private Context mContext;
private List<String> mDataSet;
private List<String> mIdevent;
public HistoryAdapter(Context context, List<String> dataSet, List<String> idevent, List<String> askPrice,
List<String> bidPrice, List<String> Profit) {
mContext = context;
mDataSet = dataSet;
mIdevent = idevent;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext)
.inflate(R.layout.layout_list_history, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Picasso.with(mContext).load(R.drawable.add2new).into(holder.image);
holder.text.setText(mDataSet.get(position));
holder.setClickListener(new HistoryAdapter.ViewHolder.ClickListener() {
public void onClick(View v, int pos, boolean isLongClick) {
if (isLongClick) {
// View v at position pos is long-clicked.
String poslx = pos + "";
String menax = mDataSet.get(pos);
Toast.makeText(mContext, "longclick pos. " + poslx + " pair " + menax, Toast.LENGTH_SHORT).show();
} else {
// View v at position pos is clicked.
//String possx = pos + "";
String poslx = pos + "";
String event2 = mDataSet.get(pos);
String id2 = mIdevent.get(pos);
Toast.makeText(mContext, "shortclick pos. " + poslx + " pair " + event2, Toast.LENGTH_SHORT).show();
//toggleSelection(pos);
Intent i = new Intent(mContext, HistoryCandlesActivity.class);
Bundle extras = new Bundle();
extras.putString("eventx", event2);
extras.putString("idx", id2);
extras.putInt("whatspage", 0);
i.putExtras(extras);
v.getContext().startActivity(i);
}
}
});
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public void remove(int position) {
mDataSet.remove(position);
notifyItemRemoved(position);
}
public void add(String text, int position) {
mDataSet.add(position, text);
notifyItemInserted(position);
}
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView image;
public TextView text;
private ClickListener clickListener;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
text = (TextView) itemView.findViewById(R.id.text);
// We set listeners to the whole item view, but we could also
// specify listeners for the title or the icon.
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
/* Interface for handling clicks - both normal and long ones. */
public interface ClickListener {
/**
* Called when the view is clicked.
*
* #param v view that is clicked
* #param position of the clicked item
* #param isLongClick true if long click, false otherwise
*/
public void onClick(View v, int position, boolean isLongClick);
}
/* Setter for listener. */
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
#Override
public void onClick(View v) {
// If not long clicked, pass last variable as false.
clickListener.onClick(v, getPosition(), false);
}
#Override
public boolean onLongClick(View v) {
// If long clicked, passed last variable as true.
clickListener.onClick(v, getPosition(), true);
return true;
}
}
}
I have implemented these lines of code but it is not working .
pagerAdapter= new AbstractPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
MyFragment frg = (MyFragment)pagerAdapter.getItem(mViewPager.getCurrentItem());
public class AbstractPagerAdapter extends FragmentPagerAdapter {
public AbstractPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return AbstractDetailFragment.newInstance(objlist.get(position),position == notePosition ? true : false);
}
#Override
public int getCount() {
return objlist.size();
}
#Override
public CharSequence getPageTitle(int position) {
return objlist.get(position).getTitle();
}
}
To get the currently visible fragment instance try the following
viewPager.setOnPageChangeListener(this);
and in the following method
#Override
public void onPageSelected(int position) {
if (position == 0)
setFragmentFor(0);
if (position == 1)
setFragmentFor(1);
.
.
.
// Upto how many fragments you've in your ViewPager
}
so in the setFragmentFor() method you should write your own logic to get the new Instance of Fragment depending upon the argument value passed over the setFragmentFor().