Following this guide, I tried implementing RecycleView into Fragments. I got the error
E/RecyclerView: No adapter attached; skipping layout
The recycle view don't display anything
I tried
recyclerview No adapter attached; skipping layout
RecyclerView in Fragment : No adapter attached skipping layout
and many more.
My Code:
package com.example.celebrity_proper;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private RecyclerView choiceRecycleView2 = null;
private ChoiceAdapter adapter = null;
private ArrayList<Choice> choiceArrayList;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Go here", "41");
View view = inflater.inflate(R.layout.fragment_main, container, false);
choiceRecycleView2 = view.findViewById(R.id.choiceRecycleView);
choiceRecycleView2.setLayoutManager(new LinearLayoutManager(getActivity()));
choiceArrayList = new ArrayList<>();
adapter = new ChoiceAdapter(getActivity(), choiceArrayList);
choiceRecycleView2.setAdapter(adapter);
createListData();
return view;
}
public void createListData() {
Choice choice = new Choice("Adolf Hitler");
choiceArrayList.add(choice);
choice = new Choice("Kim Jong Un");
Log.d("Item Count", String.valueOf(adapter.getItemCount()));
choiceArrayList.add(choice);
adapter.notifyDataSetChanged();
}
}
class Choice {
private String name;
public Choice(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
class ChoiceAdapter extends RecyclerView.Adapter<ChoiceViewHolder> {
private Context context;
private ArrayList<Choice> choices;
public ChoiceAdapter(Context context, ArrayList<Choice> choices) {
this.context = context;
this.choices = choices;
}
#NonNull
#Override
public ChoiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.choice_row, parent, false);
return new ChoiceViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ChoiceViewHolder holder, int position) {
Choice choice = choices.get(position);
holder.setDetails(choice);
}
#Override
public int getItemCount() {
return choices.size();
}
}
class ChoiceViewHolder extends RecyclerView.ViewHolder {
private TextView choice_row_text;
public ChoiceViewHolder(View view) {
super(view);
choice_row_text = view.findViewById(R.id.choice_row_text);
}
public void setDetails(Choice choice) {
choice_row_text.setText(choice.getName());
}
}
You are sending empty list to adapter constructor. Right Way
choiceRecycleView2 = view.findViewById(R.id.choiceRecycleView);
choiceRecycleView2.setLayoutManager(new LinearLayoutManager(getActivity()));
choiceArrayList = new ArrayList<>();
createListData();
adapter = new ChoiceAdapter(getActivity(), choiceArrayList);
choiceRecycleView2.setAdapter(adapter);
adapter.notifyDataSetChanged();
public void createListData() {
Choice choice = new Choice("Adolf Hitler");
choiceArrayList.add(choice);
choice = new Choice("Kim Jong Un");
Log.d("Item Count", String.valueOf(adapter.getItemCount()));
choiceArrayList.add(choice);
}
Give Orientation to LayoutManager.
Sample Code.
LinearLayoutManager manager = new LinearLayoutManager(this);
managersetOrientation(LinearLayoutManager.VERTICAL);
list.setLayoutManager(manager);
choiceRecycleView2.setAdapter( adapter );
So apparently it is an issue with AMD processor. I can't prove it since I am kicked from that class, I finished that class 2 months ago
Related
My scrolling list is displaying properly.
OnBindViewHolder is called for each item in initial display and when scrolling brings new items into view.
When I click on an item, I do see my ItemDetailsLookup and getItemDetails functions getting called, HOWEVER it doesn't call the OnBindViewHolder, and so setActivated isn't getting run.
The documentation for androidx.recyclerview.selection says "... When the user selects an item the library will record that in SelectionTracker then notify RecyclerView that the state of the item has changed. This will ultimately cause the value to be rebound by way of RecyclerView.Adapter#onBindViewHolder..." and I think I've done everything up to this point, but I must have missed something...
Any ideas?
Thanks
Here's my fragment:
package com.example.smartflashcards;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackSelectionFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
static SelectionTracker<Long> tracker;
public StackSelectionFragment() {
}
#SuppressWarnings("unused")
public static StackSelectionFragment newInstance(int columnCount) {
StackSelectionFragment fragment = new StackSelectionFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stack_selection_list, container, false);
File directory = getActivity().getFilesDir();
List<String> filesList = new ArrayList(Arrays.asList(directory.list()));
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyItemRecyclerViewAdapter(filesList));
recyclerView.getAdapter().hasStableIds();
this.tracker = new SelectionTracker.Builder<Long>(
"stack_selector",
recyclerView,
new StableIdKeyProvider(recyclerView),
new MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).build();
}
return view;
}
final class MyDetailsLookup extends ItemDetailsLookup {
private final RecyclerView mRecyclerView;
MyDetailsLookup(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
public #Nullable
ItemDetails getItemDetails(#NonNull MotionEvent e) {
View view = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(view);
if (holder instanceof MyItemRecyclerViewAdapter.ViewHolder) {
return ((MyItemRecyclerViewAdapter.ViewHolder)holder).getItemDetails();
}
}
return null;
}
}
}
Here's my adapter:
package com.example.smartflashcards;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.smartflashcards.databinding.FragmentStackSelectionBinding;
import java.util.List;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final List<String> mValues;
public MyItemRecyclerViewAdapter(List<String> items) {
setHasStableIds(true);
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(FragmentStackSelectionBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = getItemId(position);
holder.mContentView.setText(mValues.get(position));
holder.mContentView.setActivated(StackSelectionFragment.tracker.isSelected((long) position));
}
#Override
public int getItemCount() {
return mValues.size();
}
#Override
public long getItemId(int position) {
return (long)position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final TextView mIdView;
public final TextView mContentView;
public Long mItem;
public ViewHolder(FragmentStackSelectionBinding binding) {
super(binding.getRoot());
mIdView = binding.itemNumber;
mContentView = binding.content;
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails() {
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return getAbsoluteAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return mItem;
}
};
}
}
}
By following the example at https://github.com/Thumar/recyclerview-selection/tree/master/app
I was able to get it working. See my working code below.
But I still don't know which of the changes made it work and why.
If anyone figures out what was causing my problem, please post a comment or answer.
Any and all other feedback is welcome as well.
THANKS
Here's my new fragment:
package com.example.smartflashcards;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.Selection;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackSelectionFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
SelectionTracker<Long> tracker; //TODO: add private?
private StackSelectionListener listener;
public interface StackSelectionListener {
public void onSelectStack(String stack);
}
String selections = "";
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public StackSelectionFragment() {
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static StackSelectionFragment newInstance(int columnCount) {
StackSelectionFragment fragment = new StackSelectionFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stack_selection_list, container, false);
File directory = getActivity().getFilesDir();
List<String> filesList = new ArrayList(Arrays.asList(directory.list()));
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
MyItemRecyclerViewAdapter adapter = new MyItemRecyclerViewAdapter(filesList);
recyclerView.setAdapter(adapter);
adapter.hasStableIds();
this.tracker = new SelectionTracker.Builder<Long>(
"stack_selector",
recyclerView,
new StableIdKeyProvider(recyclerView),
new MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).build();
adapter.injectTracker(this.tracker);
SelectionTracker.SelectionObserver<Long> observer = new SelectionTracker.SelectionObserver<Long>() {
#Override
public void onSelectionChanged() {
super.onSelectionChanged();
//TODO: replace this placeholder action with something useful
selections = "";
tracker.getSelection().forEach(item -> selections += adapter.getContent(item.intValue()));//selections += item);
//listener.onSelectStack("selections"); //This causes an error???
Context context = getContext();
Toast toast = Toast.makeText(context, selections, Toast.LENGTH_LONG);
toast.show();
}
};
this.tracker.addObserver(observer);
}
return view;
}
final class MyDetailsLookup extends ItemDetailsLookup {
private final RecyclerView mRecyclerView;
MyDetailsLookup(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
public #Nullable
ItemDetails getItemDetails(#NonNull MotionEvent e) {
View view = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(view);
if (holder instanceof MyItemRecyclerViewAdapter.ViewHolder) {
return ((MyItemRecyclerViewAdapter.ViewHolder)holder).getItemDetails();
}
}
return null;
}
}
Here's my new adapter:
package com.example.smartflashcards;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final List<String> mValues;
private SelectionTracker<Long> selectionTracker;
public MyItemRecyclerViewAdapter(List<String> items) {
setHasStableIds(true); //TODO: remove redundancy between this and "recyclerView.getAdapter().hasStableIds()" in the Fragment
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_stack_selection, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String item = this.mValues.get(position);
holder.bind(item, selectionTracker.isSelected((long) position));
}
#Override
public int getItemCount() {
return mValues.size();
}
#Override
public long getItemId(int position) {
return (long)position;
}
public String getContent(int position) {
return mValues.get(position);
}
public void injectTracker(SelectionTracker<Long> tracker)
{
this.selectionTracker = tracker;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final TextView mContentView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mContentView = itemView.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
public void bind(String item, Boolean activate) {
this.mContentView.setText(item);
itemView.setActivated(activate); //TODO: understand how "itemView" exists outside of the constructor
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails() {
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return getAbsoluteAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return (long) getAbsoluteAdapterPosition();
}
};
}
}
}
It's a chatting application where i only wanted to display the users from database those whose numbers are available on the users device contact list.
I have got the list of contact list but i don't know how to query the database or i even tried a work around where it displays the user information who are present but those who are not present it shows a default itemview. You can check image link for reference
package com.example.myapplication;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Fragment1#newInstance} factory method to
* create an instance of this fragment.
*/
public class Fragment1 extends Fragment {
private FirebaseFirestore firebaseFirestore;
LinearLayoutManager linearLayoutManager;
private FirebaseAuth firebaseAuth;
ImageView imageViewOfUser;
FirestoreRecyclerAdapter<firebasemodel, NoteViewHolder> chatAdapter;
RecyclerView recyclerView;
ArrayList<String> contactList;
ArrayList<String> getcontactList;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1, container, false);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
recyclerView = view.findViewById(R.id.recyclerview);
contactList = new ArrayList<String>();
getcontactList = getContactList();
Query query = firebaseFirestore.collection("Users").whereNotEqualTo("uid", firebaseAuth.getUid());
FirestoreRecyclerOptions<firebasemodel> allusername = new FirestoreRecyclerOptions.Builder<firebasemodel>().setQuery(query, firebasemodel.class).build();
chatAdapter = new FirestoreRecyclerAdapter<firebasemodel, NoteViewHolder>(allusername) {
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, int i, #NonNull firebasemodel firebasemodel) {
for (String m : getcontactList) {
if (firebasemodel.getContact().equals(m)) {
noteViewHolder.particularusername.setText(firebasemodel.getName());
String uri = firebasemodel.getImage();
Picasso.get().load(uri).into(imageViewOfUser);
if (firebasemodel.getStatus().equals("Online")) {
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
noteViewHolder.statusofuser.setTextColor(Color.rgb(66, 133, 244));
} else {
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
}
noteViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked on particular user", Toast.LENGTH_SHORT).show();
}
});
} else {
//else code?
}
}
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.chatviewlayout, parent, false);
return new NoteViewHolder(view);
}
};
recyclerView.setHasFixedSize((true));
linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(chatAdapter);
return view;
}
public class NoteViewHolder extends RecyclerView.ViewHolder{
private TextView particularusername;
private TextView statusofuser;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
particularusername = itemView.findViewById(R.id.nameofuser);
statusofuser = itemView.findViewById(R.id.statusofuser);
imageViewOfUser = itemView.findViewById(R.id.imageviewofuser);
}
}
//-----------------------------------------------------------------------------------------------//
#Override
public void onStart() {
super.onStart();
chatAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if(chatAdapter!=null){
chatAdapter.stopListening();
}
}
//-----------------------------------------------------------------------------------------//
private ArrayList<String> getContactList(){
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while (phones.moveToNext()){
String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
contactList.add(phone);
}
return contactList;
}
}
I created a custom class containing the parameters for an ArrayList, the Container to the Fragments and the Fragment's classes.
Like you see:
package com.example.android.testeclickitem;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CustomClass {
private int mImage;
private String mName;
private String mLocalization;
private static int mFragmentI;
private static int mFragmentII;
private static int mFragmentIII;
public CustomClass (int image, String name, String localization, int fragmentI, int fragmentII, int fragmentIII){
mImage = image;
mName = name;
mLocalization = localization;
mFragmentI = fragmentI;
mFragmentII = fragmentII;
mFragmentIII = fragmentIII;
}
public int getImage() {
return mImage;
}
public void setImage(int mImage) {
this.mImage = mImage;
}
public String getName() {
return mName;
}
public void setName(String mName) {
this.mName = mName;
}
public String getLocalization() {
return mLocalization;
}
public void setLocalization(String mLocalization) {
this.mLocalization = mLocalization;
}
public static int getFragmentI() {return mFragmentI;}
public void setFragmentI(int mFragmentI) {
this.mFragmentI = mFragmentI;
}
public static int getFragmentII() {
return mFragmentII;
}
public void setFragmentII(int mFragmentII) {
this.mFragmentII = mFragmentII;
}
public static int getFragmentIII() {
return mFragmentIII;
}
public void setFragmentIII(int mFragmentIII) {
this.mFragmentIII = mFragmentIII;
}
public static class FragmentInflaterI extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentI(), container, false);
}
}
public static class FragmentInflaterII extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentII(), container, false);
}
}
public static class FragmentInflaterIII extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentIII(), container, false);
}
}
static class Fragments extends FragmentPagerAdapter {
public Fragments (android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new FragmentInflaterI();
} else if (position == 1){
return new FragmentInflaterII();
} else {
return new FragmentInflaterIII();
}
}
#Override
public int getCount() {
return 3;
}
}
public static class Container extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.layout_container);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.layout_container);
// Create an adapter that knows which fragment should be shown on each page
Fragments adapter = new Fragments(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
}
}
}
On main class, i added the ArrayList and the OnItemClickListener with an Intent to open the Container and Fragments:
package com.example.android.testeclickitem;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import static com.example.android.testeclickitem.CustomClass.Container;
public class Hoteis extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hoteis);
final ArrayList <CustomClass> lista = new ArrayList<>();
CustomClass hoteis = new CustomClass(0, "", "", 0, 0, 0);
hoteis.setImage(R.mipmap.ic_hotel_white_48dp);
hoteis.setName(getString(R.string.name_hotel));
hoteis.setLocalization(getString(R.string.local_hotel));
hoteis.setFragmentI(R.layout.fragment_hotel1_perfil);
hoteis.setFragmentII(R.layout.fragment_hotel1_preco);
hoteis.setFragmentIII(R.layout.fragment_hotel1_contato);
lista.add(hoteis);
CustomClass hoteis2 = new CustomClass(0, "", "", 0, 0, 0);
hoteis2.setImage(R.mipmap.ic_hotel_white_48dp);
hoteis2.setName(getString(R.string.name_hotel2));
hoteis2.setLocalization(getString(R.string.local_hotel2));
hoteis.setFragmentI(R.layout.fragment_hotel2_perfil);
hoteis.setFragmentII(R.layout.fragment_hotel2_preco);
hoteis.setFragmentIII(R.layout.fragment_hotel2_contato);
lista.add(hoteis2);
CustomClassAdapter itemAdapter = new CustomClassAdapter(this, lista);
ListView listView = (ListView) findViewById(R.id.lista_hoteis);
listView.setAdapter(itemAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent openFragment = new Intent(Hoteis.this, Container.class);
startActivity(openFragment);
}
});
}
}
The problem is: on click in any item of list, ever uses the lasts fragments declared - not the fragments declared on respective clicked item.
I try:
CustomClass customClass = list.get(position);
and
Intent openFragment = new Intent(Hoteis.this, Container.class);
startActivity(openFragment);
But doesn't works.
Does anyone know how to do the "OnItemClick" recognizes the position?
I think its because your fragments are declared as static. Because of the properties of static, your fragments are the same across all instances of CustomClass. You should read up on the static keyword here
I have set of different buttons in my list view:
This is my app:
MyBottomSheetDialogFragment:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sasank on 26-11-2016.
*/
public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
String mString;
private RecyclerView mRecyclerView;
private VerticalListAdapter mVerticalListAdapter;
static MyBottomSheetDialogFragment newInstance(String string) {
MyBottomSheetDialogFragment f = new MyBottomSheetDialogFragment();
Bundle args = new Bundle();
args.putString("string", string);
f.setArguments(args);
return f;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mString = getArguments().getString("string");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bottom_sheet_modal_list, container, false);
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<Model> list = new ArrayList<Model>();
list.add(new Model(R.drawable.ic_call_black_24dp, "Call"));
list.add(new Model(R.drawable.ic_chat_black_24dp, "Chat"));
list.add(new Model(R.drawable.ic_android_black_24dp, "Android"));
list.add(new Model(R.drawable.ic_location_on_black_24dp, "Location"));
list.add(new Model(R.drawable.ic_call_black_24dp, "Call"));
list.add(new Model(R.drawable.ic_chat_black_24dp, "Chat"));
list.add(new Model(R.drawable.ic_android_black_24dp, "Android"));
list.add(new Model(R.drawable.ic_location_on_black_24dp, "Location"));
mVerticalListAdapter = new VerticalListAdapter(getContext(), list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mVerticalListAdapter);
}
}
My verticalListAdapter.
package com.example.user.bottomsheet_android;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.MyViewHolder>{
private Context mContext;
private List<Model> mModelList;
public VerticalListAdapter(Context context, List<Model> list) {
this.mContext = context;
this.mModelList = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.modal_list_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtView.setText(mModelList.get(position).getName());
holder.imgView.setImageDrawable(mContext.getResources().getDrawable(mModelList.get(position).getImgId()));
}
#Override
public int getItemCount()
{
return mModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView txtView;
public ImageView imgView;
public MyViewHolder(View view) {
super(view);
txtView = (TextView) view.findViewById(R.id.txtView);
imgView = (ImageView) view.findViewById(R.id.imgView);
}
}
}
My goal is to add function for each button that is showed in the bottom sheet.
For any clarification please leave a comment.
In your onBindViewHolder method, I would put an onClickListener, and then use either a switch-case structure or several different if-elseif statements. For example, the switch-case would look something like:
holder.txtView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
switch (holder.getAdapterPosition()) {
case 1:
// do call related things here
.
.
.
break;
case 2:
// do chat related things here
.
.
.
break;
}
}
}
and so on. You could implement something similar with if statements
I was watch Android tutorial from Slidenerd about make Recycle View on Android. This the link: https://www.youtube.com/watch?v=OoCySqneJno.
When i make a adapter variable, i got an error. This is my full code:
NavigationDrawerFragment.java
package com.balinez.wdharmana.doahindu;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME="testpref";
public static final String KEY_USER_LEARNED_DRAWER="user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private BalinezAdapter adapter;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private View containerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer=Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER,"false"));
if(savedInstanceState!=null) {
mFromSavedInstanceState=true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView=(RecyclerView) layout.findViewById(R.id.drawer_list);
adapter = new BalinezAdapter(getActivity(),getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.ic_bookmark1, R.drawable.ic_bookmark1};
String[] titles={"Doa Sehari-Hari", "Doa Sembahyang"};
for (int i=0; i<titles.length && i<icons.length; i++) {
Information current = new Information();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if(!mUserLearnedDrawer) {
mUserLearnedDrawer=true;
saveToPreferences(getActivity(),KEY_USER_LEARNED_DRAWER,mUserLearnedDrawer+"");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if(!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences=context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName,preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences=context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
I got an error in this code:
adapter = new BalinezAdapter(getActivity(),getData());
I also include my Adapter source code:
package com.balinez.wdharmana.doahindu;
import android.content.Context;
import android.support.v7.internal.view.menu.MenuView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by WDHARMANA on 27/07/2015.
*/
public class BalinezAdapter extends RecyclerView.Adapter <BalinezAdapter.MyViewHolder> {
private LayoutInflater inflater;
List<Information> data= Collections.emptyList();
public BalinezAdapter(Context context) {
inflater=LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent,false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current=data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title= (TextView) itemView.findViewById(R.id.listText);
icon= (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
This is information.java file:
package com.balinez.wdharmana.doahindu;
/**
* Created by WDHARMANA on 27/07/2015.
*/
public class Information {
int iconId;
String title;
}
I have try solution on some Stackoverflow thread. But it doestn't work for me. If you have same problem, you can share it for us. Thanks for advance!
Your adapter constructor is
public BalinezAdapter(Context context) {
inflater=LayoutInflater.from(context);
}
While you have
new BalinezAdapter(getActivity(),getData());
You missed the second argument in the adapter.
Just change to
List<Information> data;
public BalinezAdapter(Context context,List<Information> mList) {
inflater=LayoutInflater.from(context);
data = mList;
}
and change this
#Override
public int getItemCount() {
return 0;
}
to
#Override
public int getItemCount() {
return data.size();
}