I am trying to pass a String "mMeetingKey" from View.class to PostListFragment.class, but the bundle is returning null. I checked the bundle in View.class, it is not null. When I check the bundle in PostListFragment.class, it keep returning null.
The code is mainly from "Firebase Quickstart for Database".
Thank you for your help.
View.class
public class View extends BaseActivity {
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String mMeetingKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_posts);
mViewPager = findViewById(R.id.container);
mMeetingKey=getIntent().getStringExtra("meetingKey");
Bundle bundle = new Bundle();
bundle.putString("mMeetingKey", mMeetingKey);
PostListFragment postListFragment=new PostListFragment();
postListFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container,postListFragment).commit();
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
private final Fragment[] mFragments = new Fragment[] {
new PostListFragment(),
// new MyPostsFragment(),
// new CompletedPostFragment(),
};
private final String[] mFragmentNames = new String[] {
getString(R.string.heading_recent),
//getString(R.string.heading_my_posts),
//getString(R.string.heading_completed_posts)
};
#Override
public Fragment getItem(int position) {
return mFragments[position];
}
#Override
public int getCount() {
return mFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentNames[position];
}
};
mViewPager.setAdapter(mPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Toast.makeText(this,mMeetingKey,Toast.LENGTH_LONG).show();
// Button launches NewPostActivity
findViewById(R.id.fab_new_post).setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
Intent intent = new Intent(View.this, NewPostActivity.class);
intent.putExtra("mMeetingKey",mMeetingKey);
startActivity(intent);
}
});
}
}
PostListFragment.class
public class PostListFragment extends android.support.v4.app.Fragment {
private static final String TAG = "PostListFragment";
// [START define_database_reference]
private DatabaseReference mDatabase;
// [END define_database_reference]
private String mMeetingKey;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private String meetingKeyRef;
private LinearLayoutManager mManager;
public PostListFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_post, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
meetingKeyRef = bundle.getString("mMeetingKey").toString();
}
if (bundle!= null) {
meetingKeyRef = this.getArguments().getString("mMeetingKey");
}
if (bundle == null) {
throw new IllegalArgumentException("Bundle is null");
}
// [START create_database_reference]
mDatabase = FirebaseDatabase.getInstance().getReference().child(meetingKeyRef);
// [END create_database_reference]
mRecycler = rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set up Layout Manager, reverse layout
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Set up FirebaseRecyclerAdapter with the Query
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
final DatabaseReference postRef = getRef(position);
mMeetingKey= postRef.getKey();
// Set click listener for the whole post view
final String postKey = postRef.child(mMeetingKey).getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Launch PostDetailActivity
Intent intent = new Intent(getActivity(), PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
intent.putExtra(PostDetailActivity.EXTRA_MEETING_KEY,mMeetingKey);
startActivity(intent);
}
});
// Determine if the current user has liked this post and set UI accordingly
if (model.boxCount==1) {
viewHolder.boxView.setImageResource(R.drawable.ic_toggle_check_box_checked);
} else {
viewHolder.boxView.setImageResource(R.drawable.ic_toggle_check_box_outline);
}
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
#Override
public void onClick(View boxView) {
// Need to write to both places the post is stored
DatabaseReference globalPostRef = mDatabase.child("posts").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("user-posts").child(model.uid).child(postRef.getKey());
// Run two transactions
onBoxClicked(globalPostRef);
onBoxClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
// [START post_stars_transaction]
private void onBoxClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.checkbox.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.boxCount = 0;
p.checkbox.remove(getUid());
} else {
// Star the post and add self to stars
p.boxCount = 1;
p.checkbox.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
// [END post_stars_transaction]
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.cleanup();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public Query getQuery(DatabaseReference databaseReference){
Query recentPostsQuery = databaseReference.child("posts")
.limitToFirst(100);
// [END recent_posts_query]
return recentPostsQuery;
}
}
activity_view_posts.xml
<?xml version="1.0" encoding="utf-8"?>
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tabs"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_new_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="#drawable/ic_create"
app:backgroundTint="#android:color/holo_orange_dark" />
fragment_all_post.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".checklist.View">
<android.support.v7.widget.RecyclerView
android:id="#+id/messages_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:clipToPadding="false"
android:padding="5dp"
android:scrollbars="vertical"
tools:listitem="#layout/item_post" />
You are using ViewPager then why you are replacing container with your fragment. Remove that code and use below code for View
public class View extends BaseActivity {
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String mMeetingKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_posts);
mViewPager = findViewById(R.id.container);
mMeetingKey=getIntent().getStringExtra("meetingKey");
Bundle bundle = new Bundle();
bundle.putString("mMeetingKey", mMeetingKey);
PostListFragment postListFragment=new PostListFragment();
postListFragment.setArguments(bundle);
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
private final Fragment[] mFragments = new Fragment[] {
postListFragment ,
// new MyPostsFragment(),
// new CompletedPostFragment(),
};
private final String[] mFragmentNames = new String[] {
getString(R.string.heading_recent),
//getString(R.string.heading_my_posts),
//getString(R.string.heading_completed_posts)
};
#Override
public Fragment getItem(int position) {
return mFragments[position];
}
#Override
public int getCount() {
return mFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentNames[position];
}
};
mViewPager.setAdapter(mPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Toast.makeText(this,mMeetingKey,Toast.LENGTH_LONG).show();
// Button launches NewPostActivity
findViewById(R.id.fab_new_post).setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
Intent intent = new Intent(View.this, NewPostActivity.class);
intent.putExtra("mMeetingKey",mMeetingKey);
startActivity(intent);
}
});
}
}
Related
I am trying to display news of different categories under different tabs using TabLayout. The corresponding fragments do not load at all, only the tabs are displayed. The app freezes when I try to scroll or select a tab such that even the tabIndicator barely moves to the corresponding tab and Android displays "Not responding" message.
MainActivity.java
public class MainActivity extends AppCompatActivity{
Toolbar toolbar;
TabLayout tabLayout;
ViewPager2 viewPager2;
NewsPagerAdapter newsPagerAdapter;
TabLayoutMediator tabLayoutMediator;
String[] tabTitles = new String[]{"HOME","BUSINESS","HEALTH","TECHNOLOGY","SPORTS"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.tbCustom);
tabLayout = findViewById(R.id.tlCategories); setSupportActionBar(toolbar);
viewPager2 = findViewById(R.id.vpNews);
newsPagerAdapter = new NewsPagerAdapter(getSupportFragmentManager(),getLifecycle());
viewPager2.setAdapter(newsPagerAdapter);
tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> tab.setText(tabTitles[position]));
tabLayoutMediator.attach();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());
newsPagerAdapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
tabLayout.selectTab(tabLayout.getTabAt(position));
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
tabLayoutMediator.detach();
viewPager2.setAdapter(null);
}
}
NewsPagerAdapter.java
public class NewsPagerAdapter extends FragmentStateAdapter {
public NewsPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position)
{
case 0: return new HomeFragment();
case 1: return new BusinessFragment();
case 2: return new HealthFragment();
case 3: return new TechnologyFragment();
case 4: return new SportsFragment();
default: return null;
}
}
#Override
public int getItemCount() {
return 5;
}
}
Home Fragment.java - Other fragments have the same structure
public class HomeFragment extends Fragment {
#Override
public void onDestroyView() {
super.onDestroyView();
recyclerView.setAdapter(null);
}
#Override
public void onDetach() {
super.onDetach();
}
private List<NewsModelClass> homeNews = new ArrayList<>();
String country = "in";
String category = "general";
int pageSize = 50;
private RecyclerView recyclerView;
NewsAdapter newsAdapter;
final String API_KEY = "ba88d060a3e049ca9fa46f2bea0d52c4";
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = v.findViewById(R.id.rvHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
newsAdapter = new NewsAdapter(getContext(),homeNews);
recyclerView.setAdapter(newsAdapter);
fetchNews();
}
private void fetchNews()
{
Call<NewsArticles> call = RetrofitClient.getInstance().getMyApi().getNews(country,pageSize,category,API_KEY);
call.enqueue(new Callback<NewsArticles>() {
#Override
public void onResponse(#NonNull Call<NewsArticles> call, #NonNull Response<NewsArticles> response) {
if(response.isSuccessful()) {
if (!homeNews.isEmpty()) {
homeNews.clear();
}
homeNews=response.body().getArticles();
newsAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(#NonNull Call<NewsArticles> call, Throwable t) {
Toast.makeText(getContext(),"Something is wrong",Toast.LENGTH_SHORT).show();
}
});
}
}
fragment_home.xml - Other fragments have the same layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.HomeFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rvHome"
android:fitsSystemWindows="true"
android:padding="8dp"/>
</FrameLayout>
NewsAdapter.java
public class NewsAdapter extends
RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
Context context;
List<NewsModelClass> allNews;
public NewsAdapter(Context context,List<NewsModelClass>
allNews) {
this.context = context;
this.allNews = allNews;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View newsItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
return new NewsViewHolder(newsItem);
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder holder, int position) {
NewsModelClass currentNewsItem = allNews.get(position);
holder.title.setText(currentNewsItem.getTitle());
holder.author.setText(currentNewsItem.getAuthor());
if (currentNewsItem.getUrlToImage() != null)
Glide.with(holder.itemView.getContext()).load(Uri.parse(currentNewsItem.getUrlToImage())).into(holder.articleImage);
holder.cardView.setOnClickListener(v -> {
String newsUrl = currentNewsItem.getUrl();
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
int colorInt = Color.parseColor("#F1ECC3");
CustomTabColorSchemeParams defaultColors = new CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorInt)
.build();
builder.setDefaultColorSchemeParams(defaultColors);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context, Uri.parse(newsUrl));
});
}
#Override
public int getItemCount() {
return allNews.size();
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView articleImage;
TextView title, author;
CardView cardView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
articleImage = itemView.findViewById(R.id.ivArticleImage);
title = itemView.findViewById(R.id.tvHeadline);
author = itemView.findViewById(R.id.tvAuthor);
cardView = itemView.findViewById(R.id.cardView);
}
}
}
I am a having a fragment with TabLayout. As soon as I move from TabLayout Fragment to the next Fragment and press the back key. The content on the default TabLayout fragment disappears. I found a possible solution to this in the post. Following is the code for the TabLayout.
public class IndividualCollectionSheetFragment extends MifosBaseFragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private View rootView;
public IndividualCollectionSheetFragment() {
}
public static IndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
IndividualCollectionSheetFragment fragment = new IndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_individual_recycler, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
viewPager = rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
The solution in the post suggested using getChildFramentManager instead of getSupportFragmentManager. As soon as I changed to getChildFragmentManager. I got the error.
java.lang.IllegalStateException: Fragment CollectionSheetDialogFragment{572dd42 #0 Identifier Dialog Fragment} declared target fragment NewIndividualCollectionSheetFragment{45e8153 #0 id=0x7f090361 android:switcher:2131297121:0} that does not belong to this FragmentManager!
which might be because of the class CollectionSheetDialogFragment which extends DialogFragment and there must be inconsistencies with the different Fragment Managers being used.
NewIndividualCollectionSheet.java(first fragment in tablayout)
public class NewIndividualCollectionSheetFragment extends MifosBaseFragment implements
IndividualCollectionSheetMvpView, MFDatePicker.OnDatePickListener,
Spinner.OnItemSelectedListener, View.OnClickListener {
#BindView(R.id.btn_fetch_collection_sheet)
Button btnFetchSheet;
#BindView(R.id.sp_office_list)
Spinner spOffices;
#BindView(R.id.sp_staff_list)
Spinner spStaff;
#BindView(R.id.tv_repayment_date)
TextView tvRepaymentDate;
#Inject
NewIndividualCollectionSheetPresenter presenter;
private IndividualCollectionSheet sheet;
private DialogFragment datePicker;
private RequestCollectionSheetPayload requestPayload;
private View rootView;
private ArrayAdapter<String> officeAdapter;
private ArrayList<String> officeNameList;
private List<Office> officeList;
private ArrayAdapter<String> staffAdapter;
private ArrayList<String> staffNameList;
private List<Staff> staffList;
private int officeId;
private int staffId;
private int requestCode = 1;
private boolean success = true;
private String actualDisbursementDate;
private String transactionDate;
public NewIndividualCollectionSheetFragment() {
}
public static NewIndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
NewIndividualCollectionSheetFragment fragment = new NewIndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
if (savedInstanceState != null) {
sheet = (IndividualCollectionSheet) savedInstanceState.get(
Constants.EXTRA_COLLECTION_INDIVIDUAL);
}
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_new_collection_sheet, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
presenter.attachView(this);
setUpUi();
return rootView;
}
private void setUpUi() {
setRepaymentDate();
officeNameList = new ArrayList<>();
officeAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, officeNameList);
officeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOffices.setAdapter(officeAdapter);
spOffices.setOnItemSelectedListener(this);
staffNameList = new ArrayList<>();
staffAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, staffNameList);
staffAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spStaff.setAdapter(staffAdapter);
tvRepaymentDate.setOnClickListener(this);
btnFetchSheet.setOnClickListener(this);
presenter.fetchOffices();
}
void setRepaymentDate() {
datePicker = MFDatePicker.newInsance(this);
String date = DateHelper.
getDateAsStringUsedForCollectionSheetPayload(MFDatePicker.getDatePickedAsString());
tvRepaymentDate.setText(date.replace('-', ' '));
transactionDate = date.replace('-', ' ');
actualDisbursementDate = transactionDate;
}
private void prepareRequestPayload() {
requestPayload = new RequestCollectionSheetPayload();
requestPayload.setOfficeId(officeId);
requestPayload.setStaffId(staffId);
requestPayload.setTransactionDate(tvRepaymentDate.getText().toString());
}
#Override
public void setOfficeSpinner(List<Office> offices) {
officeList = offices;
officeNameList.clear();
officeNameList.add(getString(R.string.spinner_office));
officeNameList.addAll(presenter.filterOffices(officeList));
officeAdapter.notifyDataSetChanged();
}
#Override
public void onDatePicked(String date) {
String d = DateHelper.getDateAsStringUsedForCollectionSheetPayload(date);
tvRepaymentDate.setText(d.replace('-', ' '));
}
public void retrieveCollectionSheet() {
prepareRequestPayload();
presenter.fetchIndividualCollectionSheet(requestPayload);
}
public void setTvRepaymentDate() {
datePicker.show(getActivity().getSupportFragmentManager(),
FragmentConstants.DFRAG_DATE_PICKER);
}
#Override
public void setStaffSpinner(List<Staff> staffs) {
spStaff.setOnItemSelectedListener(this);
staffList = staffs;
staffNameList.clear();
staffNameList.add(getString(R.string.spinner_staff));
staffNameList.addAll(presenter.filterStaff(staffList));
staffAdapter.notifyDataSetChanged();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()) {
case R.id.sp_office_list:
if (i == officeList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_office));
} else {
Toaster.show(rootView, officeNameList.get(i));
officeId = officeList.get(i - 1).getId();
presenter.fetchStaff(officeId);
}
break;
case R.id.sp_staff_list:
if (i == staffList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_staff));
} else {
staffId = staffList.get(i - 1).getId();
}
break;
}
}
public void popupDialog() {
CollectionSheetDialogFragment collectionSheetDialogFragment =
CollectionSheetDialogFragment.newInstance(tvRepaymentDate.getText().toString(),
sheet.getClients().size());
collectionSheetDialogFragment.setTargetFragment(this, requestCode);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_DOCUMENT_LIST);
collectionSheetDialogFragment.show(fragmentTransaction, "Identifier Dialog Fragment");
}
public void getResponse(String response) {
switch (response) {
case "FillNow":
FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack();
IndividualCollectionSheetDetailsFragment frag = new
IndividualCollectionSheetDetailsFragment().newInstance(sheet,
actualDisbursementDate, transactionDate);
((MifosBaseActivity) getActivity()).replaceFragment(frag,
true, R.id.container);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
#Override
public void showSheet(IndividualCollectionSheet individualCollectionSheet) {
sheet = individualCollectionSheet;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(Constants.EXTRA_COLLECTION_INDIVIDUAL, sheet);
}
#Override
public void showSuccess() {
if (success) {
popupDialog();
}
}
#Override
public void showError(String message) {
Toaster.show(rootView, message);
}
#Override
public void showNoSheetFound() {
success = false;
Toaster.show(rootView, getStringMessage(R.string.no_collectionsheet_found));
}
#Override
public void showProgressbar(boolean b) {
if (b) {
showMifosProgressDialog();
} else {
hideMifosProgressDialog();
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_repayment_date:
setTvRepaymentDate();
break;
case R.id.btn_fetch_collection_sheet:
retrieveCollectionSheet();
break;
}
}
}
CollectionSheetDialogFragment.java
public class CollectionSheetDialogFragment extends DialogFragment {
#BindView(R.id.tv_due_date)
TextView tvDueDate;
#BindView(R.id.tv_members)
TextView tvMembers;
#BindView(R.id.btn_fillnow)
Button btnFillnow;
#BindView(R.id.btn_cancel)
Button btnCancel;
private View rootView;
private String date;
private int members;
public CollectionSheetDialogFragment() {
}
public static CollectionSheetDialogFragment newInstance(String date, int members) {
CollectionSheetDialogFragment collectionSheetDialogFragment =
new CollectionSheetDialogFragment();
Bundle args = new Bundle();
args.putString(Constants.REPAYMENT_DATE, date);
args.putInt(Constants.MEMBERS, members);
collectionSheetDialogFragment.setArguments(args);
return collectionSheetDialogFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
date = getArguments().getString(Constants.REPAYMENT_DATE);
members = getArguments().getInt(Constants.MEMBERS);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_collection_sheet_dialog, container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tvDueDate.setText(date);
tvMembers.setText(Integer.toString(members));
}
#OnClick(R.id.btn_fillnow)
public void setBtnFillnow() {
((NewIndividualCollectionSheetFragment) getTargetFragment()).getResponse("FillNow");
}
#OnClick(R.id.btn_cancel)
public void setBtnCancel() {
getDialog().dismiss();
}
}
Can someone help me get around this error so I can persist the TabLayout On back press?
Maybe This Work :
Replace getFragmentManager() instead of getChildFragmentManager()
Try this changing seupViewPager() in IndividualCollectionSheetFragment.java like this
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
viewPager.setAdapter(adapter);
}
Image
I have an EditText which adds items to this RecyclerView and to the Realm DB. That works fine. The problem is that I don't know how to remove those items from both the RecyclerView and from the Realm DB. Should this be done on the Fragment or on the adapter? And how? Thanks!
There is an image on top showing a screenshot of the app.
Here is the Fragment where the RecyclerView is:
public class FragmentMyList extends Fragment{
private RecyclerView recyclerView;
private EditText editTxt;
private FloatingActionButton btn;
private Item item;
private ArrayList<Item> itemList;
private AdapterItemsRecycler adapterItemsRecycler;
private Realm realm;
RealmResults<Item> results;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View vistaADevolver = inflater.inflate(R.layout.fragment_my_list, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Realm.init(getContext());
realm = Realm.getDefaultInstance();
editTxt = (EditText)vistaADevolver.findViewById(R.id.editText);
btn = (FloatingActionButton) vistaADevolver.findViewById(R.id.button);
recyclerView = (RecyclerView) vistaADevolver.findViewById(R.id.recyclerViewToDo);
itemList = new ArrayList<>();
results = realm.where(Item.class).equalTo("id", 1).findAll();
final InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
adapterItemsRecycler = new AdapterItemsRecycler(results, getActivity(), new ItemsListener());
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new SimpleItemDivider(getActivity()));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapterItemsRecycler);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemName = editTxt.getText().toString();
saveIntoDatabase(itemName);
inputManager.hideSoftInputFromWindow(getView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
editTxt.getText().clear();
adapterItemsRecycler.notifyDataSetChanged();
}
});
return vistaADevolver;
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
private void saveIntoDatabase(final String itemName) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
item = bgRealm.createObject(Item.class);
item.setName(itemName);
item.setPoint(itemName);
item.setId(1);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("POINT", item.getPoint());
fragment.setArguments(bundle);
itemList.add(item);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
Log.v("database", "Stored ok");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
Log.e("database", error.getMessage());
}
});
}
class ItemsListener implements AdapterView.OnClickListener{
#Override
public void onClick(View view) {
Item itemTouched = results.get(recyclerView.getChildAdapterPosition(view));
EscuchadorInterface unEscuchador = (EscuchadorInterface)getActivity();
unEscuchador.itemSelected(itemTouched);
}
}
public interface EscuchadorInterface{
public void itemSelected(Item anItem);
}
}
My RecyclerView adapter:
public class AdapterItemsRecycler extends RecyclerView.Adapter {
private RealmResults<Item> itemList;
private Context context;
private View.OnClickListener listener;
private Realm realm;
public AdapterItemsRecycler(RealmResults<Item> itemList, Context context, View.OnClickListener listener) {
this.itemList = itemList;
this.context = context;
this.listener = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_list_detail, parent, false);
view.setOnClickListener(listener);
ItemViewHolder itemViewHolder = new ItemViewHolder(view);
return itemViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Item item = itemList.get(position);
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.loadItem(item);
}
#Override
public int getItemCount() {
return itemList.size();
}
private class ItemViewHolder extends RecyclerView.ViewHolder{
private TextView itemText;
private ImageButton imageButton;
public ItemViewHolder(View view) {
super(view);
itemText = (TextView) view.findViewById(R.id.textViewItemNameTD);
imageButton = (ImageButton) view.findViewById(R.id.delete);
}
public void loadItem(Item item) {
itemText.setText(item.getName());
imageButton.setImageResource(R.drawable.trash);
}
public ImageButton getImageButton() {
return imageButton;
}
}
}
RecyclerView's detail:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:context="com.segunfamisa.sample.bottomnav.MainActivity">
<ImageButton
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tint="#03A9F4"
android:scaleType="centerInside"
android:background="#ffffff"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:onClick="deleteItem"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewItemNameTD"
android:textSize="14dp"
android:textColor="#212121"
android:background="#ffffff"
android:padding="10dp"
android:layout_toRightOf="#+id/delete"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow"
android:scaleType="centerInside"
android:background="#ffffff"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
Just use RealmRecyclerViewAdapter with the RealmResults directly, which handles synchronization between database and list and adapter automatically.
public class FragmentMyList
extends Fragment {
private RecyclerView recyclerView;
private EditText editTxt;
private FloatingActionButton btn;
private AdapterItemsRecycler adapterItemsRecycler;
private Realm realm;
RealmResults<Item> results;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View vistaADevolver = inflater.inflate(R.layout.fragment_my_list, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Realm.init(getContext());
realm = Realm.getDefaultInstance();
editTxt = (EditText) vistaADevolver.findViewById(R.id.editText);
btn = (FloatingActionButton) vistaADevolver.findViewById(R.id.button);
recyclerView = (RecyclerView) vistaADevolver.findViewById(R.id.recyclerViewToDo);
results = realm.where(Item.class).equalTo("id", 1).findAll();
final InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
adapterItemsRecycler = new AdapterItemsRecycler(results, new ItemsListener());
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new SimpleItemDivider(getActivity()));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapterItemsRecycler);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String itemName = editTxt.getText().toString();
saveIntoDatabase(itemName);
inputManager.hideSoftInputFromWindow(getView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
editTxt.getText().clear();
}
});
return vistaADevolver;
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
private void saveIntoDatabase(final String itemName) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
Item item = bgRealm.createObject(Item.class);
item.setName(itemName);
item.setPoint(itemName);
item.setId(1);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
Log.v("database", "Stored ok");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
Log.e("database", error.getMessage());
}
});
}
class ItemsListener
implements AdapterView.OnClickListener {
#Override
public void onClick(View view) {
Item itemTouched = results.get(recyclerView.getChildAdapterPosition(view));
EscuchadorInterface unEscuchador = (EscuchadorInterface) getActivity();
unEscuchador.itemSelected(itemTouched);
}
}
public interface EscuchadorInterface {
public void itemSelected(Item anItem);
}
}
// compile 'io.realm:android-adapters:2.0.0'
public class AdapterItemsRecycler
extends RealmRecyclerViewAdapter<Item, ItemViewHolder> {
private View.OnClickListener listener;
public AdapterItemsRecycler(OrderedRealmCollection<Item> itemList, View.OnClickListener listener) {
super(itemList, true);
this.listener = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.my_list_detail, parent, false);
view.setOnClickListener(listener);
ItemViewHolder itemViewHolder = new ItemViewHolder(view);
return itemViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Item item = getData().get(position);
ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
itemViewHolder.loadItem(item);
}
private static class ItemViewHolder
extends RecyclerView.ViewHolder {
private TextView itemText;
private ImageButton imageButton;
public ItemViewHolder(View view) {
super(view);
itemText = (TextView) view.findViewById(R.id.textViewItemNameTD);
imageButton = (ImageButton) view.findViewById(R.id.delete);
}
public void loadItem(Item item) {
itemText.setText(item.getName());
imageButton.setImageResource(R.drawable.trash);
}
public ImageButton getImageButton() {
return imageButton;
}
}
}
private void deleteFromDatabase(final String itemName) {
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgRealm) {
Item item = bgRealm.where(Item.class).equalTo("name", itemName).findFirst();
if(item != null) {
item.deleteFromRealm();
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
Log.v("database", "Delete ok");
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
Log.e("database", error.getMessage());
}
});
}
I want to create navigation drawer sub category like TOI app. So far I have done this(some part of the code):
main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
android:name="com.medical.medicaldialogue.Activity.FragmentDrawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener{
private static String TAG = MainActivity.class.getSimpleName();
public static int SELECTED_POSITION = 0;
private SearchView searchView;
private Toolbar toolbar;
private ImageView imageViewToolbar;
private FragmentDrawer drawerFragment;
private ArrayList<HomeSummary> summaryItemArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
summaryItemArrayList = (ArrayList<HomeSummary>)getIntent().getSerializableExtra("summaryList");
Log.d("arrayLength -", ""+summaryItemArrayList.size());
toolbar =(Toolbar)findViewById(R.id.app_bar);
imageViewToolbar = (ImageView)findViewById(R.id.app_bar_img);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position){
Bundle bundle = new Bundle();
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position){
case 0:
fragment = new EditorPicsFragment();
title = getString(R.string.title_home);
imageViewToolbar.setVisibility(View.VISIBLE);
break;
}
if(fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
bundle.putString("myFragment",title);
if(title.equalsIgnoreCase("Title")){
bundle.putParcelableArrayList("summaryList", summaryItemArrayList);
} else if(title.equalsIgnoreCase("Editor's Pick")){
bundle.putString("cat_id", "56");
}
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the app_bar title
getSupportActionBar().setTitle(title);
PrefStore.setStoryBarTitle(MainActivity.this, title);
}
}
#Override
protected void onResume() {
super.onResume();
// displayView(0);
}
}
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles= null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
// Required empty public constructor
Log.d(TAG, "Drawer fragment created 1111");
}
public void setDrawerListener(FragmentDrawerListener listener){
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData(){
List<NavDrawerItem> data = new ArrayList<>();
// Preparing navigation drawer items
for(int i=0; i<titles.length; i++){
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
/**
* Modified Date on 9/2/2016
* Resizing the Drawer width when
*/
if(position ==21) {
ViewGroup.LayoutParams params = containerView.getLayoutParams();
params.width = 250;
containerView.setLayoutParams(params);
}else {
// ViewGroup.LayoutParams params = containerView.getLayoutParams();
// params.width = 400;
// containerView.setLayoutParams(params);
mDrawerLayout.closeDrawer(containerView);
}
Log.d(TAG, "Postion clicked: "+position);
}
#Override
public void onLongClick(View view, int position) {
Log.d(TAG, "Long press");
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
Log.d("Drawer opened","");
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
// drawerListener.onDrawerItemSelected(drawerView, 4);
// toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
Log.d("syncState", "Drawer");
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener{
public void onDrawerItemSelected(View view, int position);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "Drawer fragment created onStart() 222222");
}
}
so far I am able to create navigation drawer. But I want to achieve like this
How to add sub category drawer in above code. Any help would be appreciated.
I have a fragment with a list of recipes. But I can't get the onItemClick to work...
I have tried it with onListItemClick but that didn't seem to work either.
My Fragment
public class RecipeBookListViewFragment extends ListFragment implements AdapterView.OnItemClickListener {
private List<Recipe> recipes;
private DataPassListener mCallback;
private ListView recipeList;
public interface DataPassListener{
public void passData(Recipe recipe);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
RecipeBookActivity.CONTEXT = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recipeitem_list, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fillRecipeBook();
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Recipe recipe = (Recipe) getListAdapter().getItem(position);
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "halloooooo...");
mCallback.passData(recipe);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
recipeList = getListView();
recipeList.setClickable(true);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try {
mCallback = (DataPassListener)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataPassListener");
}
}
private void fillRecipeBook(){
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "loading...");
RestClient.ApiInterface service = RestClient.getClient();
Call<List<Recipe>> call = service.recipes();
call.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(Response<List<Recipe>> response, Retrofit retrofit) {
dialog.dismiss();
Log.d("MainActivity", "Status Code = " + response.code());
if (response.isSuccess()) {
// request successful (status code 200, 201)
recipes = response.body();
ArrayAdapter<String> adapter = new RecipeListAdapter(getActivity(), recipes);
setListAdapter(adapter);
} else {
// response received but request not successful (like 400,401,403 etc)
//Handle errors
}
}
#Override
public void onFailure(Throwable t) {
Log.d("MainActivity", "GOE KAPOT " + t.getMessage());
dialog.dismiss();
}
});
}
}
my ListView.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView android:id="#android:id/list" android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#FFCC00"
android:dividerHeight="2dp"/>
<TextView android:id="#+id/recipe_title" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="left"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
My custom adapter
public class RecipeListAdapter extends ArrayAdapter{
private Context context;
private boolean useList = true;
private List<Recipe> recipes;
public RecipeListAdapter(Context context, List<Recipe> recipes) {
super(context,-1, recipes);
this.context = context;
this.recipes = recipes;
}
private class ViewHolder{
TextView titleText;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Recipe recipe = (Recipe)getItem(position);
View viewToUse;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if(useList){
viewToUse = mInflater.inflate(R.layout.fragment_recipeitem_list, null);
} else {
viewToUse = mInflater.inflate(R.layout.fragment_recipeitem_grid, null);
}
holder = new ViewHolder();
holder.titleText = (TextView)viewToUse.findViewById(R.id.recipe_title);
viewToUse.setTag(holder);
} else {
viewToUse = convertView;
holder = (ViewHolder) viewToUse.getTag();
}
holder.titleText.setText(recipe.getTitle());
return viewToUse;
}
}
my main activity:
public class RecipeBookActivity extends Activity implements DataPassListener {
public static Context CONTEXT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
if(findViewById(R.id.recipe_list_fragment) != null){
if (savedInstanceState != null)
return;
RecipeBookListViewFragment recipeBookListViewFragmentFragment = new RecipeBookListViewFragment();
recipeBookListViewFragmentFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.recipe_list_fragment,
recipeBookListViewFragmentFragment).commit();
}
}
#Override
public void passData(Recipe recipe){
RecipeFragment recipeFragment = new RecipeFragment();
Bundle args = new Bundle();
args.putSerializable(recipeFragment.DATA_RECEIVE, recipe);
recipeFragment.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.recipe_list_fragment, recipeFragment)
.commit();
}
}
You need to set the onItemClickListener to the ListView before it can register any clicks. Change your onViewCreated code to:
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
recipeList = getListView();
recipeList.setOnItemClickListener(this);
}
That way any item clicks on the ListView will be handled in the onItemClick() method that is overidden in the Fragment.