How to navigate to a fragment from recyclerview? - android

I have a recyclerview (with an adapter) in my mainactivity which displays different categories, I want to click on each of these categories and navigate to a fragment from there. How do I do this? What is the best approach?
Here is the mainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_info_layout);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("");
myToolbar.setTitle(Html.fromHtml("<font color='#272d85'> </font>"));
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter();
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView)
MenuItemCompat.getActionView(searchItem);
searchItem.expandActionView();
searchView.requestFocus();
searchView.setQueryHint("Sök efter ord");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
My adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private Context context;
private int[] cardimages = {
R.drawable.stockholm,
R.drawable.invandrar,
R.drawable.goteborg,
R.drawable.norrland,
R.drawable.svengelska,
R.drawable.skanska,
R.drawable.ovrigt
};
private String[] titles = {
"Stockholmsslang",
"Invandrarslang",
"Skane",
"Norrland",
"Svengelska",
"Skåne",
"Övrigt",
};
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView itemImage;
public ViewHolder(View itemView) {
super(itemView);
itemImage = (ImageView) itemView.findViewById(R.id.item_image);
itemImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int position = getAdapterPosition();
//ONclick for the recyclerview
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view;
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recylerview_main, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
Context context = viewHolder.itemView.getContext();
Picasso.with(context).load(cardimages[i]).fit().centerInside().into(((MyAdapter.ViewHolder) viewHolder).itemImage);
}
#Override
public int getItemCount() {
return titles.length;
}
}

You can't initiate a fragment like activity.You need a parent view to initiate the fragment.In your case,I suppose you want to show it in a new screen.
Create a new activity with a framelayout in layout,send the fragment name to the activity and use this code.If you have multiple fragments, you can use one activity for all fragments by using extras.
Intent i = new Intent(context,FragmentParentActivity.class);
i.putExtra("fragment",1);
startActivity(i);
you can use the extra parameter to decide which fragment to initiate,(onCreate)
String fragmentTag="Fragment1";
int fragmentID = getIntent().getIntExtra("fragment",0);
if(fragmentID == 1){
fragment = new YourFragment();
}
...
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_frame, fragment, fragmentTag).commit();

Declare this method in your Fragment where you are initializing the adapter.
If you are using activity then remove getActivity() while initializing FragmentManager.You also need to have a framelayout in your current activity at the position you want to place your fragment.
public void replaceFragment()
{
YourFragment yourFragment=new YourFragment();
FragmentManager fragmentManager=getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, yourFragment,null);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commitAllowingStateLoss();
}
Now call this method from the adapter
#Override
public void onClick(View view) {
final int position = getAdapterPosition();
(Activity)context.replaceFragment();
}
});
//Initilaize ypu adapter in activity like this:
//Declare varaible is adapter
MyAdapter myAdapter=new MyAdapter(this);
In your adapter create a constructor
public MyAdapter(Context context)
{
this.context=context;
}

You can easily navigate to any fragment from a fragment or a RecyclerAdapter using:
AppCompatActivity activity = (AppCompatActivity) view.getContext();
// view is from onClick listener in my case
YourFrag frag = new YourFrag();
activity.getSypportFragmentManager().beginTransaction(R.id.yourFragmentHolder,frag).addToBackStack(null).commit();

Related

Recyclerview item onClick to open a fragment from Main Activity Fragment

i have 4-5 fragments on MainActivity and on host fragment i have a recyclerview. on each item of recycler i have to open a fragment out of 4 more and kill the current fragment on which recycler is placed. i couldnt achieve this.
here is my MainActivity where all fragments are placed and host fragment is homefragment where recycler is placed and i want to move from homefragment to another fragment when 0th item clicked
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_house_business, R.id.nav_committees,
R.id.nav_senators, R.id.nav_about_senate, R.id.nav_publications, R.id.nav_media_center
, R.id.nav_get_involved)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
here is my host fragment
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
TextView ticker ;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
final View root = inflater.inflate(R.layout.fragment_home, container, false);
MyListData[] myListData = new MyListData[] {
new MyListData("Order of the Day", R.drawable.orders),
new MyListData("Bills", R.drawable.bills),
new MyListData("Delete", R.drawable.orders),
new MyListData("Dialer", R.drawable.bills),
new MyListData("Alert", R.drawable.orders),
new MyListData("Map", R.drawable.bills),
new MyListData("Email", R.drawable.orders),
new MyListData("Info", R.drawable.bills),
new MyListData("Delete", android.R.drawable.ic_delete),
new MyListData("Dialer", android.R.drawable.ic_dialog_dialer),
new MyListData("Alert", android.R.drawable.ic_dialog_alert),
new MyListData("Map", android.R.drawable.ic_dialog_map),
};
RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
MyListAdapter adapter = new MyListAdapter(myListData);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
//recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
return root;
}
}
here is my listadapter
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder>{
private MyListData[] listdata;
// RecyclerView recyclerView;
public MyListAdapter(MyListData[] listdata) {
this.listdata = listdata;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final MyListData myListData = listdata[position];
holder.textView.setText(listdata[position].getDescription());
holder.imageView.setImageResource(listdata[position].getImgId());
switch(position)
{
case 0 :
{
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment someFragment = new Orderofday();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, someFragment ); // give your fragment container id in first parameter
transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
}
});
}
case 1 :
{
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"click on item: "+myListData.getDescription(),Toast.LENGTH_LONG).show();
}
});
}
case 2 :
{
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"click on item: "+myListData.getDescription(),Toast.LENGTH_LONG).show();
}
});
}
case 3 :
{
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"click on item: "+myListData.getDescription(),Toast.LENGTH_LONG).show();
}
});
}
case 4 :
{
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"click on item: "+myListData.getDescription(),Toast.LENGTH_LONG).show();
}
});
}
case 5 :
{
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"click on item: "+myListData.getDescription(),Toast.LENGTH_LONG).show();
}
});
}
default:
{
break;
}
}
}
#Override
public int getItemCount() {
return listdata.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView textView;
public RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
this.imageView = (ImageView) itemView.findViewById(R.id.imageView);
this.textView = (TextView) itemView.findViewById(R.id.textView);
relativeLayout = (RelativeLayout)itemView.findViewById(R.id.relativeLayout);
}
}
when case 0 is clicked i need to kill the current homefragment and move to another fragment but couldnt do it kindly somebody help me to achieve this
In this solution i'm not using Navigation Library
replace fragments on MainActivity . you should create interface in your adapter class and home fragment:
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder>{
private OnItemClickListener onItemClickListener;
//...
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(position, onItemClickListener);
}
//...
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imageView;
public TextView textView;
public RelativeLayout relativeLayout;
private OnItemClickListener listener;
public ViewHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
textView = (TextView) itemView.findViewById(R.id.textView);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.relativeLayout);
}
public void bind(int position, OnItemClickListener listener) {
this.listener = listener;
final MyListData myListData = listdata[position];
textView.setText(listdata[position].getDescription());
imageView.setImageResource(listdata[position].getImgId());
relativeLayout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (listener != null) {
listener.onClick(getAdapterPosition());
}
}
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.onItemClickListener = listener;
}
public interface OnItemClickListener{
void onClick(int position);
}
}
in HomeFragment:
public class HomeFragment extends Fragment implements
MyListAdapter.OnItemClickListener {
private OnItemClickListener onItemClickListener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
//...
adapter.setOnItemClickListener(this);
//...
}
#Override
public void onClick(int position) {
if (onItemClickListener != null)
onItemClickListener.onClick(position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener{
void onClick(int position);
}
}
in MainActivity:
public class MainActivity extends AppCompatActivity implements
HomeFragment.OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
HomeFragment homeFragment = new HomeFragment();
homeFragment.setOnItemClickListener(this);
getSupportFragmentManager().beginTransaction()
.replace(R.id.your_frame_layout, homeFragment).commit();
}
//...
#Override
public void onClick(int position) {
switch (position){
case 0:
//replace fragment
break;
//...
}
}
}

Android - Do something every time I switch from fragments

I have an activity that has two fragments. The activity has a custom toolbar and the remaining space on the screen is used by the fragments (one at a time). In this toolbar there is a SearchView.OnQueryTextListener but this search should always be available in the fragment 1 and for the fragment 2 if should be available only if it meets a criteria. So what I need is a way to check, everytime I switch from fragments which one if occupying the screen at the moment and if it's the fragment one I set the searchView as available and for the fragment 2 the searchView will be available only if it meets the criteria.
This is my Activity:
public class ActivityTeams extends BaseActivity implements SearchView.OnQueryTextListener {
public ActivityTeams(){
super(R.layout.activity_teams);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
token = SharedPrefsHelper.getString(getApplicationContext(), Constants.TOKEN);
listview = (ListView) findViewById(R.id.listview);
listview.setVisibility(View.INVISIBLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new InternsFragment(), getResources().getString(R.string.team_internal));
adapter.addFragment(new ExternsFragment(), getResources().getString(R.string.team_external));
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);
}
}
#Override
protected void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if(toolbar!=null) {
if (user_type == 1) {
toolbar.setTitle(R.string.collaborators_title);
} else if (user_type == 2) {
toolbar.setTitle(R.string.admin_title);
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_action_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search_team, menu);
SearchManager searchManager = (SearchManager)
getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchMenuItem.getActionView();
ImageView searchSubmit = (ImageView) searchView.findViewById (android.support.v7.appcompat.R.id.search_go_btn);
searchSubmit.setImageResource(R.drawable.ic_dots_w);
searchSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Clear query
searchView.setQuery("", false);
//Collapse the action view
searchView.onActionViewCollapsed();
//Collapse the search widget
searchMenuItem.collapseActionView();
listview.setVisibility(View.GONE);
viewPager.bringToFront();
appBarLayout.setVisibility(View.VISIBLE);
}
});
for (TextView textView : findChildrenByClass(searchView, TextView.class)) {
textView.setTextColor(Color.BLACK);
textView.setHintTextColor(Color.BLACK);
}
searchView.setSearchableInfo(searchManager.
getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return true;
}
This is fragment 1:
public class InternsFragment extends Fragment{
public InternsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_interns, container, false);
return rootView;
}
And this is fragment 2:
public class ExternsFragment extends Fragment {
public ExternsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_externs, container, false);
return rootView;
}
searchMenuItem in my activity is the thing I want to make change the visibility depending on the fragment that it's visible.
Use a ViewPager.OnPageChangeListener and use InvalidateOptionsMenu() inside that like so:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentFragment = position // use a field to store position
invalidateOptionsMenu();
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
});
Then depending on position, setup your menu in onPrepareOptionsMenu

How to implement a Fragment in RecyclerView.Adapter

Good day How can I call a fragment when the users will click the card inside MyAdapter class. I want to replace view from the adapter. I am using recyclerview wants to perform click event using the view from my row layout.
Like for example when the user clicks the card it will open a fragment and it will show more data. Hope you can help me guys.
This is my main fragment
AccountsFragment
ReceivableFragment
LoanAppFragment
Those fragments hold different data. when the user clicks the cards inside that fragment it will call another fragment the SLDTLFragment.
Btw this MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Datas> mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
public CardView mCardView;
public TextView account_type;
public TextView accnt_description;
public TextView balance_label;
public TextView account_balance;
public MyViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
account_type = (TextView) v.findViewById(R.id.lblShareCapital);
balance_label = (TextView) v.findViewById(R.id.lblAvailableBalance);
accnt_description = (TextView) v.findViewById(R.id.sl_desc);
account_balance = (TextView) v.findViewById(R.id.actual_balance);
}
}
public MyAdapter(List<Datas> myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
//holder.account_type.setText(mDataset[position]);
Datas datas = mDataset.get(position);
holder.accnt_description.setText(datas.getSL_DESC());
holder.account_balance.setText(datas.getACTUAL_BALANCE());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String sl_desc = mDataset.get(position).getSL_DESC();
// String actual_balance = mDataset.get(position).getACTUAL_BALANCE();
String sle = mDataset.get(position).getSLE();
String slc = mDataset.get(position).getSLC();
String slt = mDataset.get(position).getSLT();
String ref_no = mDataset.get(position).getREF();
Log.d("CardView Clicked", "sle code: " + sle);
Log.d("CardView Clicked", "slc code: " + slc);
Log.d("CardView Clicked", "slt code: " + slt);
Log.d("CardView Clicked", "ref no: " + ref_no);
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
AccountsFragment.java
public class AccountsFragment extends Fragment {
private SQLiteHandler db;
public AccountsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_accounts, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
SQLiteHandler db = new SQLiteHandler(getActivity());
MyAdapter adapter = new MyAdapter(db.getUserSLDetails());
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
ReceivableFragment.java
public class ReceivableFragment extends Fragment {
public ReceivableFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_receivable, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
SQLiteHandler db = new SQLiteHandler(getActivity());
MyAdapter adapter = new MyAdapter(db.getUserSLARLoans());
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView nav_header_name;
private TextView nav_header_email;
public TextView txtLogOut;
private SQLiteHandler db;
private SessionManager session;
private Timer timer;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Will replace the activity_main.xml to relativelayout_for_fragment.xml
if (savedInstanceState == null) {
AccountsFragment f1= new AccountsFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.relativelayout_for_fragment, f1);// relativelayout_for_fragment is inside the content_main.xml
fragmentTransaction.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View header=navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
txtLogOut = (TextView) findViewById(R.id.nav_logout_menu);
int id = item.getItemId();
if (id == R.id.nav_deposit) {
// Handle the preference action
AccountsFragment accounts= new AccountsFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relativelayout_for_fragment, accounts)
.commit();
Toast.makeText(MainActivity.this, "Deposit Accounts", Toast.LENGTH_SHORT).show();
}else if (id == R.id.nav_receivable) {
// Handle the Loan application();
ReceivableFragment receivable= new ReceivableFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relativelayout_for_fragment, receivable)
.commit();
Toast.makeText(MainActivity.this, "AR and Loan Accounts", Toast.LENGTH_SHORT).show();
}else if (id == R.id.nav_apply_loan_menu) {
// Handle the Loan application();
LoanAppFragment loan_app= new LoanAppFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relativelayout_for_fragment, loan_app)
.commit();
Toast.makeText(MainActivity.this, "This module is under developement", Toast.LENGTH_SHORT).show();
}else if (id == R.id.nav_logout_menu) {
// Handle the About action
logoutUser();
//Toast.makeText(MainActivity.this, "successfully Logout", Toast.LENGTH_LONG).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
nav_header_name = (TextView) header.findViewById(R.id.nav_name);
nav_header_email = (TextView) header.findViewById(R.id.nav_email);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
//Fetching user details from SQLite
HashMap<String, String> user = db.getUserDetails();
String username = user.get("username");
String email = user.get("email");
//Displaying the user info in nav_header_main.xml
nav_header_name.setText(username);
nav_header_email.setText(email);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
db.deleteUserSLDTL();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
#Override
protected void onPause() {
super.onPause();
timer = new Timer();
Log.i("Main", "Invoking logout timer");
LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
timer.schedule(logoutTimeTask, 30000); // auto logout in 30secs inactivity
Log.i("Main", "Log out user due to inactivity");
}
#Override
protected void onResume() {
super.onResume();
if (timer != null) {
timer.cancel();
Log.i("Main", "cancel timer");
timer = null;
}
}
private class LogOutTimerTask extends TimerTask {
#Override
public void run() {
session.setLogin(false);
db.deleteUsers();
db.deleteUserSLDTL();
//redirect user to login screen
Intent i = new Intent(MainActivity.this, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
}
You need to use Listener/Callback pattern to inform your Activity or Fragment where the Adapter is used. Do not directly call a Fragment or activity inside of the Adapter because it will defeat the purpose of the Adapter. Adapter should only be used to show the data.
To implement the pattern, first create the interface and constructor to set the listener in your Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
...
private List<Datas> mDataset;
private ClickListener mListener;
public interface ClickListener {
void onItemClicked(YourData yourData);
}
public MyAdapter(List<Datas> myDataset, ClickListener listener) {
mDataset = myDataset;
mListener = listener;
}
...
}
Second, whenever there is a click of the item data, tell the listener with the following code in your Adapter:
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
...
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String sl_desc = mDataset.get(position).getSL_DESC();
// String actual_balance = mDataset.get(position).getACTUAL_BALANCE();
// String sle = mDataset.get(position).getSLE();
// String slc = mDataset.get(position).getSLC();
// String slt = mDataset.get(position).getSLT();
// String ref_no = mDataset.get(position).getREF();
// Simplify the above to a pojo. We assume the pojo is YourData
YourData data = new YourData();
// set the data from above.
mListener.onItemClicked(yourData);
});
}
Third, you need to set the listener in your Activity/Fragment which using the Adapter with:
MyAdapter.ClickListener listener = new MyAdapter.ClickListener() {
#Override
public void onItemClicked(YourData yourData) {
// Do something with the data here.
}
};
MyAdapter adapter = new MyAdapter(db.getUserSLARLoans(), listener);
rv.setAdapter(adapter);
You need to handle the data in your listener inside the onItemClicked() method above.
try to pass getFragmentManager using constructor and then replace the view with container view in your item row.
//constructor
public MyAdapter(FragmentManager fragment, List<Datas> myDataset) {
mDataset = myDataset;
mFragment = fragment;
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView mCardView;
public TextView account_type;
public TextView accnt_description;
public TextView balance_label;
public TextView account_balance;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
account_type = (TextView) v.findViewById(R.id.lblShareCapital);
balance_label = (TextView) v.findViewById(R.id.lblAvailableBalance);
accnt_description = (TextView) v.findViewById(R.id.sl_desc);
account_balance = (TextView) v.findViewById(R.id.actual_balance);
mCardView.setOnClickListener(this)
}
#Override
public void onClick(View view){
mFragment.beginTransaction().replace(R.id.containerRow,new MyFragment()).commit();
}
}
//note this is not tested code.

refresh fragment after changing data in database

there is a MainActivity with it's fragment named FragmentOne. i have a List of items in this fragment and these data are save in my database
i make changes from NavigationView in MainActivity .. i try to delete all rows from my database. it works, but after that i need to refresh my FragmentOne, how can i refresh the FragmentOne UI ?
i have a method named updateUI in my FragmentOne but how could i access that method? when i make that method public everything just goes wrong!
i tested different ways but failed.. can anybody tell me how can i do this?
MainActivity :
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private TabLayout tabLayout;
private ViewPager viewPager;
private Detail mDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//////// TOOLBAR
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
///////// DRAWER
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView =
(NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener
(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_item_one:
return false;
case R.id.nav_item_two:
AlertDialog.Builder alert_delete = new AlertDialog.Builder(
MainActivity.this);
alert_delete.setTitle("Alert!");
alert_delete.setMessage(R.string.alert_delete_all);
alert_delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DetailLab.get(getApplicationContext()).deleteAllDetail();
FragmentOne fragmentOne = new FragmentOne();
fragmentOne.getFragmentManager().beginTransaction().replace(R.id.card_view, fragmentOne)
.commit();
dialog.dismiss();
}
});
alert_delete.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert_delete.show();
return false;
..
..
case R.id.nav_item_nine:
finish();
default:
return false;
}
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "ONE");
adapter.addFragment(new FragmentTwo(), "TWO");
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 null;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
here is my method for delete all rows from database in another class called DetailLab :
public void deleteAllDetail() {
mDatabase.delete(DetailTable.NAME, null, null); }
and this is my FragmentOne:
public class FragmentOne extends Fragment {
private static final String SAVED_NUMBER_VISIBLE = "number";
private RecyclerView mDetailRecyclerView;
private DetailAdapter mAdapter;
private boolean mNumberVisible;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one_layout,
container, false);
mDetailRecyclerView = (RecyclerView)
view.findViewById(R.id.detail_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true); //This will reverse the data order but not scroll the RecyclerView to the last item
layoutManager.setStackFromEnd(true); //For keeping data order same and simply scrolling the RecyclerView to the last item
mDetailRecyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null) {
mNumberVisible =
savedInstanceState.getBoolean(SAVED_NUMBER_VISIBLE);
}
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_NUMBER_VISIBLE, mNumberVisible);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_one_layout, menu);
MenuItem numberItem = menu.findItem(R.id.show_numbers);
if (mNumberVisible) {
numberItem.setTitle(R.string.hide_numbers);
} else {
numberItem.setTitle(R.string.show_numbers);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.show_numbers:
mNumberVisible = !mNumberVisible;
getActivity().invalidateOptionsMenu();
updateNumbers();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateNumbers() {
DetailLab detailLab = DetailLab.get(getActivity());
int detailCount = detailLab.getDetails().size();
String number = getResources().getQuantityString
(R.plurals.number_plural, detailCount, detailCount);
if (!mNumberVisible) {
number = null;
}
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(number);
}
private void updateUI() {
DetailLab detailLab = DetailLab.get(getActivity());
List<Detail> details = detailLab.getDetails();
if (details.size() == 0) {
TextView t = (TextView) view.findViewById(R.id.empty);
t.setText(R.string.empty_view);
t.setVisibility(View.VISIBLE);
} else {
TextView t = (TextView) view.findViewById(R.id.empty);
t.setVisibility(View.GONE);
}
// Toast.makeText(getContext(), "zero", Toast.LENGTH_SHORT).show();
if (mAdapter == null) {
mAdapter = new DetailAdapter(details);
mDetailRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setDetails(details);
mAdapter.notifyDataSetChanged();
}
updateNumbers();
}
private class DetailHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private TextView mTitleTextView;
// private TextView mDateTextView;
private Detail mDetail;
private RatingBar mRatingBar;
public DetailHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_detail,
parent, false));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.detail_title);
// mDateTextView = (TextView) itemView.findViewById(R.id.detail_date);
mRatingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
}
public void bind(Detail detail) {
mDetail = detail;
mTitleTextView.setText(mDetail.getTitle());
mRatingBar.setRating(mDetail.getRate());
}
#Override
public void onClick(View view) {
Intent intent = DetailPagerActivity.newIntent(getActivity(),
mDetail.getId());
startActivity(intent);
}
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(
getActivity());
alert.setMessage(R.string.alert);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DetailLab.get(getActivity()).deleteDetail(mDetail);
updateUI();
updateNumbers();
dialog.dismiss();
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
return true;
}
}
private class DetailAdapter extends RecyclerView.Adapter<DetailHolder> {
private List<Detail> mDetails;
public DetailAdapter(List<Detail> details) {
mDetails = details;
}
#Override
public DetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(getActivity());
return new DetailHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(DetailHolder holder, int position) {
Detail detail = mDetails.get(position);
holder.bind(detail);
}
#Override
public int getItemCount() {
return mDetails.size();
}
public void setDetails(List<Detail> details) {
mDetails = details;
}
}
}
and here is my layout for FragmentOne :
<RelativeLayout
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:id="#+id/fragment_one_layout">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/detail_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:textAlignment="center"
android:textSize="20sp"/>
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="24dp"
android:layout_marginBottom="24dp"
android:src="#drawable/ic_menu_add"
android:scaleType="center"
app:elevation="8dp"
app:borderWidth="0dp"
/>
my logcat:
FATAL EXCEPTION: main
Process: com.drgnme.listhamrah, PID: 23454
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()' on a null object reference
at com.drgnme.listhamrah.MainActivity$1$1.onClick(MainActivity.java:76)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I think you are having this issue because of the below code in your MainActivity:
FragmentOne fragmentOne = new FragmentOne();
fragmentOne.getFragmentManager().beginTransaction().replace(R.id.card_view, fragmentOne).commit();
You try to get the instance of the fragment manager with getFragmentManager() who call Activity.getFragmentManager but your fragmentOne isn't attach to the activity so the method return null and you get a java.lang.NullPointerException
Instead of fragmentOne.getFragmentManager() use getSupportFragmentManager() directly from the activity.
Hope this helps.
I have a method named updateUI in my FragmentOne but how could i
access that method?
To call the updateUI method of your FragmentOne
alert_delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DetailLab.get(getApplicationContext()).deleteAllDetail();
Fragment page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + ViewPager.getCurrentItem());
// based on the current position you can then cast the page to the correct
// class and call the method:
if (ViewPager.getCurrentItem() == 0 && page != null) {
((FragmentOne)page).updateUI();
}
dialog.dismiss();
}
});
To refresh a fragment's UI, use the fragment manager to detach and attach the same fragment again.
Eg:
public void refreshFragmentUI(Fragment fragment) {
getSupportFragmentManager()
.beginTransaction()
.detach(fragment)
.attach(fragment)
.commit();
}
Note: Use getSupportFragmentManager() if you are using support libraries. Else use getFragmentManager()
The best way to update data from SQLite Database in fragment is using LoaderManager.LoaderCallbacks and CursorAdapter. Because it is an Asynchronous process.

SetOnItemClickListener not working inside Fragment

I am using RecycleView to display list of Name and Description. I am using Fragment to view the desired layout. Now, I want to open new Activity onItemClick. I have declared SetOnItemClickListener inside the Fragment, i.e. in "View onCreateView". But it is not working. Here is my code:
This is my java class:
public class TabsHeaderActivity extends AppCompatActivity {
private static final String TAG = TabsHeaderActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs_header);
final Toolbar toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) getSupportActionBar().setTitle("TECHNOLOGY");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ViewPager viewPager = (ViewPager) findViewById(R.id.htab_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
tabLayout.setupWithViewPager(viewPager);
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.htab_collapse_toolbar);
try {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.header);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#SuppressWarnings("ResourceType")
#Override
public void onGenerated(Palette palette) {
int vibrantColor = palette.getVibrantColor(R.color.primary_500);
int vibrantDarkColor = palette.getDarkVibrantColor(R.color.primary_700);
collapsingToolbarLayout.setContentScrimColor(vibrantColor);
collapsingToolbarLayout.setStatusBarScrimColor(vibrantDarkColor);
}
});
} catch (Exception e) {
// if Bitmap fetch fails, fallback to primary colors
Log.e(TAG, "onCreate: failed to create bitmap from background", e.fillInStackTrace());
collapsingToolbarLayout.setContentScrimColor(
ContextCompat.getColor(this, R.color.primary_500)
);
collapsingToolbarLayout.setStatusBarScrimColor(
ContextCompat.getColor(this, R.color.primary_700)
);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
Log.d(TAG, "onTabSelected: pos: " + tab.getPosition());
switch (tab.getPosition()) {
case 0:
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.cyan_50)), "Cyan");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.amber_50)), "Amber");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.purple_50)), "Purple");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.grey)), "Grey");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem searchItem = menu.findItem(R.id.menuSearch);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private static 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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public static class DummyFragment extends Fragment {
int color;
Intent intent;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
DessertAdapter adapter = new DessertAdapter(getContext());
recyclerView.setAdapter(adapter);
adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){
#Override
public void onItemClick(View view, int position) {
switch (position) {
case 3:
intent = new Intent(view.getContext(), LaunchScreenActivity.class);
startActivity(intent);
}
}
});
return view;
}
}
}
This is my Adapter class:
public class DessertAdapter extends RecyclerView.Adapter<DessertAdapter.DessertVh> {
private List<Dessert> desserts = new ArrayList<>();
OnItemClickListener clickListener;
private Context context;
public DessertAdapter(Context context) {
this.context = context;
desserts = Dessert.prepareDesserts(
context.getResources().getStringArray(R.array.dessert_names),
context.getResources().getStringArray(R.array.dessert_descriptions));
}
#Override
public DessertVh onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_dessert, parent, false);
return new DessertAdapter.DessertVh(view);
}
#Override
public void onBindViewHolder(DessertVh holder, int position) {
Dessert dessert = desserts.get(position);
holder.mName.setText(dessert.getName());
holder.mDescription.setText(dessert.getDescription());
holder.mFirstLetter.setText(String.valueOf(dessert.getFirstLetter()));
}
#Override
public int getItemCount() {
return desserts == null ? 0 : desserts.size();
}
public class DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView mName;
private TextView mDescription;
private TextView mFirstLetter;
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(v, getPosition());
}
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
I am not sure what I am doing wrong. I have checked it in debugger mode. I have put a breakpoint at line:
adapter.SetOnItemClickListener(new DessertAdapter.OnItemClickListener(){
Now, when my Activity is loading debugger comes on this line but, doesn't go inside it. But, when I am clicking something, the debugger doesn't even come on this line, means when I am clicking an item, SetOnItemClickListener doesn't get triggered.
My xml code is:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dummyfrag_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_light">
<android.support.v7.widget.RecyclerView
android:id="#+id/dummyfrag_scrollableview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_horizontal_margin" />
</FrameLayout>
Well, you implemented a normal click listener
DessertVh extends RecyclerView.ViewHolder implements View.OnClickListener
But you never set it.
public DessertVh(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.txt_name);
mDescription = (TextView) itemView.findViewById(R.id.txt_desc);
mFirstLetter = (TextView) itemView.findViewById(R.id.txt_firstletter);
}
Did you forget about itemView.setOnClickListener(this)?

Categories

Resources