I have the code for a fragment of the as follows that works very well:
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
private boolean mSubtitleVisible;
private static final String SAVED_SUBTITLE_VISIBLE = "subtitle";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_crime_list,container,false);
mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (null != savedInstanceState) {mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);}
updateUI();
return view;
}
#Override
public void onResume()
{
super.onResume();
updateUI();
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_SUBTITLE_VISIBLE, mSubtitleVisible);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem subtitleItem = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible) {subtitleItem.setTitle(R.string.hide_subtitle);}
else {subtitleItem.setTitle(R.string.show_subtitle);}
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_item_new_crime:
{
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
}
case R.id.menu_item_show_subtitle:
{
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateSubtitle();
return true;
}
default: return super.onOptionsItemSelected(item);
}
}
private void updateSubtitle()
{
CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeCount = crimeLab.getCrimes().size();
String subtitle = getString(R.string.subtitle_format,crimeCount);
if (!mSubtitleVisible) {subtitle = null;}
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
private void updateUI()
{
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes =crimeLab.getCrimes();
if (null == mAdapter)
{
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
else {mAdapter.notifyDataSetChanged();}
updateSubtitle();
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
//public TextView mTitleTextView;
private TextView mTitleTextView;
private TextView mDateTextView;
private CheckBox mSolvedCheckBox;
private Crime mCrime;
public CrimeHolder(View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
//mTitleTextView = (TextView) itemView;
mTitleTextView = (TextView) itemView.findViewById(R.id.list_item_crime_title_text_view);
mDateTextView = (TextView) itemView.findViewById(R.id.list_item_crime_date_text_view);
mSolvedCheckBox = (CheckBox) itemView.findViewById(R.id.list_item_crime_solved_check_box);
}
public void bindCrime(Crime crime)
{
mCrime = crime;
mTitleTextView.setText(mCrime.getTitle());
mDateTextView.setText(mCrime.getDate().toString());
mSolvedCheckBox.setChecked(mCrime.isSolved());
}
#Override
public void onClick(View v)
{
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder>
{
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes){mCrimes = crimes;}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_crime/*android.R.layout.simple_list_item_1*/,parent,false);
return new CrimeHolder(view);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) //finalmente a esta de aquĆ
{
Crime crime = mCrimes.get(position);
/*holder.mTitleTextView.setText(crime.getTitle());*/
holder.bindCrime(crime);
}
#Override
public int getItemCount()
{
return mCrimes.size();
}
}
}
I have tried to implement the examples of Drag and Swipe with RecyclerView, like this medium article:
But I only get errors.
What do I need to implement onSwiped and where?
Thanks
Related
I am trying to add an contact object and the way I do it is when the user hits add button in the menu bar; this is how I do it.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_contact:
Contact contact = new Contact();
ContactLab.get(getActivity()).addContact(contact);
updateUI();
mCallbacks.onContactSelected(contact);
return true;
case R.id.action_edit:
return true;
case R.id.action_delete:
ContactLab crimeLab = ContactLab.get(getActivity());
crimeLab.deleteContact(mContact);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I have the following fragment
public class ContactListFragment extends Fragment {
// private static final String SAVED_SUBTITLE_VISIBLE = "subtitle";
private static final String ARG_CRIME_ID = "crime_id";
private RecyclerView mCrimeRecyclerView;
private ContactAdapter mAdapter;
public Contact mContact;
private Callbacks mCallbacks;
/**
* Required interface for hosting activities.
*/
public interface Callbacks {
void onContactSelected(Contact contact);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCallbacks = (Callbacks) context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.contact_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (savedInstanceState != null) {
}
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
private void updateSubtitle() {
ContactLab crimeLab = ContactLab.get(getActivity());
int contactCount = crimeLab.getContacts().size();
String subtitle = getString(R.string.subtitle_format, contactCount);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
public void updateUI() {
ContactLab crimeLab = ContactLab.get(getActivity());
List<Contact> contacts = crimeLab.getContacts();
if (mAdapter == null) {
mAdapter = new ContactAdapter(contacts);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setContacts(contacts);
mAdapter.notifyDataSetChanged();
}
updateSubtitle();
}
private class ContactHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private TextView mTitleTextView;
public ContactHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_content, parent, false));
itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.content_name);
}
public void bind(Contact contact) {
mContact = contact;
mTitleTextView.setText(mContact.getName());
}
#Override
public void onClick(View view) {
mCallbacks.onContactSelected(mContact);
}
}
private class ContactAdapter extends RecyclerView.Adapter<ContactHolder> {
private List<Contact> mContacts;
public ContactAdapter(List<Contact> crimes) {
mContacts = crimes;
}
#Override
public ContactHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new ContactHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(ContactHolder holder, int position) {
Contact contact=mContacts.get(position);
holder.bind(contact);
}
#Override
public int getItemCount() {
return mContacts.size();
}
public void setContacts(List<Contact> contacts) {
mContacts = contacts;
}
}
and then I start the above fragment from the following activity fragment
public class ContactListActivity extends SingleFragmentActivity
implements ContactListFragment.Callbacks, ContactFragment.Callbacks {
#Override
protected Fragment createFragment() {
return new ContactListFragment();
}
#Override
protected int getLayoutResId() {
return R.layout.activity_masterdetail;
}
#Override
public void onContactSelected(Contact contact) {
if (findViewById(R.id.detail_fragment_container) == null) {
Intent intent = ContactPagerActivity.newIntent(this, contact.getIDD());
startActivity(intent);
} else {
Fragment newDetail = ContactFragment.newInstance(contact.getId());
getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_fragment_container, newDetail)
.commit();
}
}
public void onContactUpdated(Contact crime) {
ContactListFragment listFragment = (ContactListFragment)
getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
listFragment.updateUI();
}
}
could any one show me whre I am doing wrong because I see the followoig error in my log
Process: com.bignerdranch.android.adressbook, PID: 28871
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.bignerdranch.android.adressbook.Contact.getName()' on a null object reference
atcom.bignerdranch.android.adressbook.ContactFragment.onCreateView(ContactFragment.java:82)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
I have a SwitchTabActivty with 4 items. In my case, I use the second item to get some data from the web through a recyclerview. The problem is that when I press the fourth item (it contains a button that's starting an activity) and I go back to my second tab , my recycler view is multiplied with the same data again.
Switchtabactivity :
public class SwitchTabActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private boolean pressToExit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.weather_tab);
tabLayout.getTabAt(1).setIcon(R.drawable.events);
tabLayout.getTabAt(2).setIcon(R.drawable.details_tab);
tabLayout.getTabAt(3).setIcon(R.drawable.settings_tab);
setColorTab(tabLayout);
}
private void setColorTab(TabLayout tab) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors, null));
} else {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
if (!pressToExit) {
Toast.makeText(this, "Press back again to exit.", Toast.LENGTH_SHORT).show();
pressToExit = true;
} else {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onResume() {
super.onResume();
pressToExit = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_switch_tab, 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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return WeatherFragment.newInstance(position);
case 1:
return EventFragment.newInstance(position);
case 2:
return OwnEventFragment.newInstance(position);
case 3:
return SettingsFragment.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Weather";
case 1:
return "Events";
case 2:
return "My Events";
case 3:
return "Settings";
}
return null;
}
}
EventFragment :
public class EventFragment extends Fragment implements EventResponse {
private String latitude, longitude;
private static final String ARG_SECTION_NUMBER = "section_number";
private RecyclerView eventList;
private EventAdapter adapter;
private TextView ifNullEvents;
private final ArrayList<EventData> eventsData = new ArrayList<>();
private UserDataBase db;
private List<String> latLonList;
private ProgressBar progressBar;
public EventFragment() {
}
public static EventFragment newInstance(int sectionNumber) {
EventFragment fragment = new EventFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.event_fragment, container, false);
initView(rootView);
db = new UserDataBase(getContext());
checkLocationChanged();
latLonList = db.getLatLon();
latitude = latLonList.get(0);
longitude = latLonList.get(1);
String EVENT_BRITE_URL_PARSE = "MY_URL";
String EVENT_BRITE_TOKEN = "MY_TOKEN";
new EventBriteApi(this, getContext()).execute(EVENT_BRITE_URL_PARSE + EVENT_BRITE_TOKEN);
setupRecyclerView();
setLocationMessage();
return rootView;
}
private void initView(View view) {
eventList = (RecyclerView) view.findViewById(R.id.event_recycler_view);
ifNullEvents = (TextView) view.findViewById(R.id.text_null_location);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar_event);
}
private void checkLocationChanged() {
if (WePrefs.isLocationChanged) {
eventsData.clear();
ifNullEvents.setText(getResources().getString(R.string.waiting_for_data));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
WePrefs.setIsLocationChanged(false);
} else {
progressBar.setVisibility(View.GONE);
ifNullEvents.setVisibility(View.GONE);
}
if (WePrefs.isNullEventLocation) {
ifNullEvents.setText(getResources().getString(R.string.no_events_found));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
WePrefs.setIsNullEventLocation(false);
}
}
private void setupRecyclerView() {
eventList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
eventList.setLayoutManager(linearLayoutManager);
adapter = new EventAdapter(getActivity(), eventsData);
adapter.setHasStableIds(true);
eventList.setAdapter(adapter);
}
#Override
public void onResume() {
checkLocationChanged();
setLocationMessage();
super.onResume();
}
private void setLocationMessage() {
if (eventsData.isEmpty()) {
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
} else {
ifNullEvents.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
progressBar.setVisibility(View.GONE);
}
#Override
public void getArray(ArrayList<EventData> data) {
eventsData.clear();
eventsData.addAll(new ArrayList<>(new LinkedHashSet<>(data)));
}
}
Adapter :
ublic class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventHolder> {
ArrayList<EventData> data;
Context context;
public EventAdapter(Context context, ArrayList<EventData> events) {
this.context = context;
data = events;
}
#Override
public EventHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RelativeLayout layout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.single_event_view, parent, false);
return new EventAdapter.EventHolder(layout);
}
#Override
public void onBindViewHolder(EventHolder holder, int position) {
holder.eventName.setText(data.get(position).getEventName());
if (data.get(position).getEventImageUrl() != null) {
Picasso.with(context).load(data.get(position).getEventImageUrl()).into(holder.eventPic);
} else {
holder.eventPic.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.no_image));
}
}
#Override
public int getItemCount() {
return data.size();
}
public class EventHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView eventName;
ImageView eventPic;
RelativeLayout layout;
public EventHolder(View itemView) {
super(itemView);
eventName = (TextView) itemView.findViewById(R.id.event_name);
eventPic = (ImageView) itemView.findViewById(R.id.event_image);
layout = (RelativeLayout) itemView.findViewById(R.id.event_layout);
layout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
//context.startActivity(new Intent(context, WebViewActivity.class));
}
}
}
Those are some of my java classes that I use for this kind of thing.
Anyway, another problem is that, when I change the location ( to receive my events) I must go to another tab and after that to come back to see my events list ( I think it needs to recreate the view ) so , because of that I called onResume, but it does not help.
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)?
I've a viewpager looping a multiple fragments and set in a viewpager. Each fragment has a listview with checkbox. On clicking any one item of a list it will notify all the fragments so that all checkbox remains unchecked and only clicked item will be checked.
CreateGroupStep1
public class CreateGroupStep1 extends BaseActivity implements IGroup {
private TabLayout tabLayout;
private ViewPager viewPager;
private ImageView next_btn,back;
private int current_item_position;
private ViewPagerAdapter adapter;
private ArrayList<Interest> interestList;
ArrayList<String>al_sports;
ArrayList<String>al_list_collect;
private ArrayList<String>al_title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group_step1);
storeDataOfArrayList();
al_list_collect=new ArrayList<String>();
initViews();
}
public void initViews() {
viewPager = (ViewPager) findViewById(R.id.viewpager);
RelativeLayout back=(RelativeLayout) findViewById(R.id.back);
back=(RelativeLayout) findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
next_btn=(ImageView) findViewById(R.id.next_btn);
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent ii=new Intent(CreateGroupStep1.this,CreateGroupStep2.class);
//startActivity(ii);
Toast.makeText(CreateGroupStep1.this, "", Toast.LENGTH_SHORT).show();
}
});
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(CreateGroupStep1.this.getSupportFragmentManager());
for (int i=0;i<al_title.size();i++)
{
adapter.addFragment(InterestFragmentForGroup.getInstance(al_sports),al_title.get(i));
viewPager.setAdapter(adapter);
}
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(10);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
current_item_position = position;
// Toast.makeText(CreateGroupStep1.this, "scrolled", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onClickedNextButton(final String message) {
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CreateGroupStep1.this,message, Toast.LENGTH_SHORT).show();
}
});
}
public 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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public void storeDataOfArrayList()
{
saveData();
al_sports=new ArrayList<>();
al_sports.add("Baseball");
al_sports.add("Basketball");
al_sports.add("Bowling");
al_sports.add("Cricket");
al_sports.add("Football");
al_sports.add("Golf");
al_sports.add("Handball");
al_sports.add("Hockey");
al_sports.add("Jogging");
al_sports.add("Racquetball");
al_sports.add("Running");
al_sports.add("Skiing");
al_sports.add("Snowboarding");
al_sports.add("Soccer");
al_sports.add("Swimming");
al_sports.add("Tennis");
}
private void saveData()
{
al_title=new ArrayList<String>();
al_title.add("Sports");
al_title.add("LifeStyle");
al_title.add("Adventure");
al_title.add("Recreation");
al_title.add("The Arts");
al_title.add("College");
al_title.add("Sos");
al_title.add("Industry");
al_title.add("LocalBiz");
al_title.add("Corporate");
}
}
InterestAdapterForGroup
public class InterestAdapterForGroup extends RecyclerView.Adapter<InterestAdapterForGroup.MyViewHolder> implements IGroup {
public int selectedPosition = -1;
IGroup inter;
private LayoutInflater inflater;
private ArrayList<Interest> stList;
private Context mContext;
private ArrayList<Interest> checked_item = new ArrayList<>();
public InterestAdapterForGroup(Context context, ArrayList<Interest> al_list) {
this.mContext = context;
this.stList = al_list;
inflater = LayoutInflater.from(context);
inter = (IGroup) mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_ethnic, parent, false);
InterestAdapterForGroup.MyViewHolder holder = new InterestAdapterForGroup.MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final int pos = position;
final Interest interest = stList.get(position);
holder.title.setText(interest.getName());
if (position == selectedPosition) {
holder.chkSelected.setChecked(true);
} else {
holder.chkSelected.setChecked(false);
}
holder.chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isPressed()) {
interest.isSelected = isChecked;
if (isChecked) {
checked_item.clear();
checked_item.add(interest);
selectedPosition = position;
} else {
checked_item.remove(interest);
selectedPosition = -1;
}
notifyDataSetChanged();
}
}
});
clickedItems();
}
public void clickedItems() {
if (checked_item.size() > 0) {
if (Constants.GLOBAL_ARRAY.size() > 0) {
Constants.GLOBAL_ARRAY.clear();
for (int i = 0; i < checked_item.size(); i++) {
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
}
}
ArrayList<String> al_name = new ArrayList<String>();
ArrayList<String> al_nam = new ArrayList<String>();
for (int i = 0; i < checked_item.size(); i++) {
al_name.add(checked_item.get(i).getEmailId());
}
for (int i = 0; i < checked_item.size(); i++) {
al_nam.add(checked_item.get(i).getName());
Constants.GLOBAL_ARRAY.add(checked_item.get(i).getName());
}
inter.onClickedNextButton(al_nam.toString());
}
public ArrayList<Interest> getCheckedItemList() {
return stList;
}
#Override
public int getItemCount() {
return stList.size();
}
#Override
public void onClickedNextButton(String message) {
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CheckBox chkSelected;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_ethnic);
chkSelected = (CheckBox) itemView
.findViewById(R.id.chk);
}
#Override
public void onClick(View v) {
}
}
}
InterestFragmentForGroup
public class InterestFragmentForGroup extends BasePagerFragment implements IPager {
private ArrayList<String> interestList;
private ArrayList<Interest> interestListfunction;
public static Fragment getInstance(ArrayList<String> interestList){
Bundle bundle = new Bundle();
bundle.putSerializable("interestList",interestList);
InterestFragmentForGroup interestsFragment = new InterestFragmentForGroup();
interestsFragment.setArguments(bundle);
return interestsFragment;
}
public void getInterestList(){
interestList = (ArrayList<String>) getArguments().getSerializable("interestList");
}
private RecyclerView recyclerView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sports_fragment, container, false);
initViews(rootView);
return rootView;
}
public void initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.drawerList);
getInterestList();
setData();
}
public void setData() {
interestListfunction = new ArrayList<>();
for (int i = 0; i < interestList.size(); i++) {
Interest st = new Interest(interestList.get(i), interestList.get(i), false);
interestListfunction.add(st);
}
adapter2 = new InterestAdapterForGroup(getActivity(), interestListfunction);
recyclerView.addItemDecoration(new DividerDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(adapter2);
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
}
}
I have a MainActivity and Three Fragments with recyclerViews inside the three fragments, the recyclerview contain two textviews, i want the user to click on the recyclerview and the text in should be passed on to the new activity, i am a little bit new so i would appreciate it if you can give me detailed code and some explanation.
I want to click on an item in the recyclerview and that should open a new activity, data(text) should be passed from the recyclerview to the new activity.
Here is my code for the HymnModel.java
public class HymnModel {
String title;
String song;
HymnModel(String title, String song){
this.title=title;
this.song=song;
}
public String getTitle() {return title;
}
public String getSong() {
return song;
}
}
Here is the code for ItemVeiwHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.tutorialsbuzz.recyclerview.R;
public class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView title_textview;
public TextView song_textview;
public ItemViewHolder(View itemView) {
super(itemView);
itemView.setClickable(true);
title_textview = (TextView) itemView.findViewById(R.id.song_title);
song_textview = (TextView) itemView.findViewById(R.id.song);
}
public void bind(HymnModel hymnModel) {
title_textview.setText(hymnModel.getTitle());
song_textview.setText(hymnModel.getSong());
}
}
Here is my Adapter class
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tutorialsbuzz.recyclerview.R;
import java.util.ArrayList;
import java.util.List;
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private List<HymnModel> mCountryModel;
private List<HymnModel> mOriginalCountryModel;
public RVAdapter(List<HymnModel> mCountryModel) {
this.mCountryModel = mCountryModel;
this.mOriginalCountryModel = mCountryModel;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);
return new ItemViewHolder(view);
}
#Override
public int getItemCount() {
return mCountryModel.size();
}
public void setFilter(List<HymnModel> countryModels){
mCountryModel = new ArrayList<>();
mCountryModel.addAll(countryModels);
notifyDataSetChanged();
}
}
Here is the code for one my fragments
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView recyclerview;
private List<HymnModel> mHymnModel;
private RVAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_one_fragment, container, false);
recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerview.setLayoutManager(layoutManager);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
int numOfSongs = 32;
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
String [] titles = {HymnTitles.hymnTitle1, HymnTitles.hymnTitle2, HymnTitles.hymnTitle3, HymnTitles.hymnTitle4, HymnTitles.hymnTitle5,
HymnTitles.hymnTitle6, HymnTitles.hymnTitle7, HymnTitles.hymnTitle8, HymnTitles.hymnTitle9, HymnTitles.hymnTitle10, HymnTitles.hymnTitle11,
HymnTitles.hymnTitle12};
String [] songs = {Hymns.hymn1.substring(width/5), Hymns.hymn2, Hymns.hymn3, Hymns.hymn4, Hymns.hymn5, Hymns.hymn6, Hymns.hymn7, Hymns.hymn8, Hymns.hymn9, Hymns.hymn10, Hymns.hymn11, Hymns.hymn12};
mHymnModel = new ArrayList<>();
for (int i = 0; i < titles.length; i++) {
mHymnModel.add(new HymnModel(i + "." + " " + titles[i], " " + songs[i]));
}
adapter = new RVAdapter(mHymnModel);
recyclerview.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(item,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
adapter.setFilter(mHymnModel);
return true; // Return true to collapse action view
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
}
#Override
public boolean onQueryTextChange(String newText) {
final List<HymnModel> filteredModelList = filter(mHymnModel, newText);
adapter.setFilter(filteredModelList);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<HymnModel> filter(List<HymnModel> models, String query) {
query = query.toLowerCase();
final List<HymnModel> filteredModelList = new ArrayList<>();
for (HymnModel model : models) {
final String text = model.getSong().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
My MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_person,
R.drawable.ic_action_group,
R.drawable.ic_action_call
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TabOneFragment(), "Tab 1");
adapter.addFragment(new TabTwoFragment(), "Tab 2");
adapter.addFragment(new TabThreeFragment(), "Tab 3");
viewPager.setAdapter(adapter);
}
}
And lastly my ViewPageAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
Thank You.
Create an interface
public interface OnHymnClickListener {
void onHymnClick(HymnModel hymnModel);
}
Pass the listener to the adapter
public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
private OnHymnClickListener listener;
public void setListener(OnHymnClickListener listener) {
this.listener = listener;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, int i) {
final HymnModel model = mCountryModel.get(i);
itemViewHolder.bind(model);
itemViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null) {
listener.onHymnClick(model);
}
}
});
}
}
Let your fragment implement it
public class TabOneFragment extends Fragment implements SearchView.OnQueryTextListener, OnHymnClickListener {
#Override
public void onHymnClick(HymnModel hymnModel) {
//put data to bundle and startActivity
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
adapter = new RVAdapter(mHymnModel);
adapter.setListener(this);
recyclerview.setAdapter(adapter);
}
}
Hello first of all you always want to start your activity from activity or fragment.
Never start it from adapter.
So in your adapter constructor add this
public AdapterName(......,Context context){
...your code.
this.mContext=context;
}
pass context there.
and than inside this method
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mContext instanceof YourActivityName){
((YourActivityName)mContext).yourDesiredMethod();
}
}
});