Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708
The Item i am spawning in:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="#+id/show_chat_single_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="70dp"
app:cardBackgroundColor="#dcdada"
app:cardCornerRadius="0dp"
app:contentPadding="3dp"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="2dp"
card_view:cardUseCompatPadding="true">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/chat_persion_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/chat_persion_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="0dp"
android:text="Name"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintLeft_toRightOf="#+id/chat_persion_image"
app:layout_constraintTop_toTopOf="#+id/chat_persion_image" />
<TextView
android:id="#+id/chat_persion_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginTop="8dp"
android:text="Email"
app:layout_constraintLeft_toLeftOf="#+id/chat_persion_name"
app:layout_constraintTop_toBottomOf="#+id/chat_persion_name" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
My conversation layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/msgs_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:theme="#style/AppTheme2"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/active_chats"
android:layout_width="match_parent"
android:layout_height="510dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="57dp">
</android.support.v7.widget.RecyclerView>
<include
android:id="#+id/include2"
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
My Adapter:
public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
private ArrayList<User> mUsers;
private Context mContext;
public ActiveChatConvo(ArrayList<User> photos,Context dick) {
mUsers = photos;
mContext = dick;
}
private Context getContext() {
return mContext;
}
#Override
public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get the data model based on position
User user = mUsers.get(position);
// Set item views based on your views and data model
TextView name = holder.mItemName;
name.setText(user.getName());
TextView description = holder.mItemDescription;
description.setText(user.getEmail());
ImageView pic = holder.mItemImage;
Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mItemImage;
private TextView mItemName;
private TextView mItemDescription;
private LinearLayout layout;
final LinearLayout.LayoutParams params;
public ViewHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Context context = itemView.getContext();
Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
//showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
context.startActivity(showChatIntent);
}
}
}
My main class
public class ConnectionsActivity extends AppCompatActivity {
private Toolbar toolbar;
private ViewPager mViewPager;
private TextView person_name,person_email;
private RecyclerView recyclerView;
private DatabaseReference mRef;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<User> users;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connections);
//Database
mRef = FirebaseDatabase.getInstance().getReference("Users");
mRef.keepSynced(true);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
users = new ArrayList<>();
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String name = postSnapshot.child("Name").getValue(String.class);
String email = postSnapshot.child("Email").getValue(String.class);
String pic = postSnapshot.child("image").getValue(String.class);
users.add(new User(name,email,pic));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Recycler View
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
//VIEWS
toolbar = (Toolbar) findViewById(R.id.tToolbar);
if (toolbar != null)
setSupportActionBar(toolbar);
ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);
profileActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
startActivity(profileActivity);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
});
homeActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
startActivity(home);
finish();
overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
});
}
}
So if the recyclerView Activity is the first activity I visit then it will not create the items.
Firebase is synchronize so it doesn't block the main thread of your application, that mean that your application continue executing, you need to notify the adapter after firebase finishing his job by using adapter.notifiyDatasetChanged() after the for loop
Replace this:
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
recyclerView.setAdapter(adapter);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
with this:
recyclerView = (RecyclerView)findViewById(R.id.active_chats);
ActiveChatConvo adapter = new ActiveChatConvo(users,this);
mLinearLayoutManager = new LinearLayoutManager(this);
//mLinearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(mLinearLayoutManager);
recyclerView.setAdapter(adapter);
You need to set adapter after you set LayoutManager.
In my case I managed to solve it I found a way to start FirebaseDatabase before opening the activity and added the cod
adapter.notifyDataSetChanged();
and then I started the firebase before opening it with this
FirebaseDatabase.getInstance().getReference().keepSynced(true);
You can use Boolean button to check if it is true adapter is made
Related
my question is is there a way to save the SpamCount of a ReciclerView in SharedPreferences?
I try to make a List that can change the view from a "List mode" to "Grid mode" and save that information in SharedPreferences so that the "List View" will remain after killing the app.
The example of what I am trying to do would be the following ...
example of what i try to do on button click
And the code that I try to change is the following ...
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static RecyclerView recyclerView;
private ReciclerAdapter reciclerAdapter;
ImageView viewGridS, viewListS;
SharedPreferences vSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recicler_main);
vSettings = this.getSharedPreferences("Vision", 0);
notesRecyclerView = findViewById(R.id.recycler_view);
notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
viewListS = findViewById(R.id.viewList);
viewGridS = findViewById(R.id.viewGrid);
#Override
public void onClick(View v) {
SharedPreferences vSettings = this.getSharedPreferences("Vision", 0);
SharedPreferences.Editor viEdit = vSettings.edit();
switch (v.getId())
{
case R.id.viewList:
viewGridS.setVisibility(View.GONE);
viewListS.setVisibility(View.VISIBLE);
viEdit.putString("Vision",listView());
viEdit.apply();
break;
case R.id.viewGrid:
viewListS.setVisibility(View.GONE);
viewGridS.setVisibility(View.VISIBLE);
listWiew();
viEdit.putString("Vision",gridView());
viEdit.apply();
break;
}
});
}
public int gridView(){
notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
return null;
}
public int listView(){
notesRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
return null;
}
}
When trying to start the Activity the RecyclerView does not show anything and the button does not work.
if someone could help me I would appreciate it in advance ... thanks
You have done couple of things wrong here.
Incorrect use of SharedPreferences
Adapter on RecycleView not setup
Manage LinearLayout and StaggeredGridLayoutManager
I will try to accomplished kind similar end result which you are looking for, a simple button which is switching layout on click. Code as follows -
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String LIST_VIEW = "List View";
private String GRID_VIEW = "Grid View";
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private SharedPreferences sharedPreferences;
private RecycleViewAdapter recycleViewAdapter;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Simple List setup for data to show in recycle view
List<String> stringList = new ArrayList<>();
stringList.add("Monday\nI'll ask her out.");
stringList.add("Tuesday");
stringList.add("Wednesday\nI'll take her to garden to talk.");
stringList.add("Thursday\nI'll give her a gift");
stringList.add("Friday");
stringList.add("Saturday");
stringList.add("Sunday\nI'll propose her. ");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
recyclerView = findViewById(R.id.recycler_view);
recycleViewAdapter = new RecycleViewAdapter(this, stringList);
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
/*
* SharedPreferences value will be null for very first install of app
* ELSE SharedPreferences will have use last saved value
* */
String CURRENT_VIEW = sharedPreferences.getString("LAYOUT_TYPE", null);
if (CURRENT_VIEW == null) {
CURRENT_VIEW = LIST_VIEW;
sharedPreferences.edit().putString("LAYOUT_TYPE", LIST_VIEW).apply();
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(recycleViewAdapter);
} else
switchView(CURRENT_VIEW);
Button buttonPanel = findViewById(R.id.buttonPanel);
buttonPanel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sharedPreferences.getString("LAYOUT_TYPE", null).equals(LIST_VIEW))
switchView(GRID_VIEW);
else
switchView(LIST_VIEW);
}
});
}
/*
* Method will switch Layout on RecycleView and update new Adapter
* #param: Required Layout Type (LIST_VIEW or GRID_VIEW)
* */
private void switchView(String layoutTypeValue) {
if (layoutTypeValue.equals(LIST_VIEW))
recyclerView.setLayoutManager(linearLayoutManager);
else if (layoutTypeValue.equals(GRID_VIEW))
recyclerView.setLayoutManager(staggeredGridLayoutManager);
sharedPreferences.edit().putString("LAYOUT_TYPE", layoutTypeValue).apply();
recyclerView.setAdapter(recycleViewAdapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:padding="8dp"
android:layout_margin="16dp"
android:layout_gravity="end|bottom"
android:id="#+id/buttonPanel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:background="#android:color/holo_orange_dark"
android:text="Change Layout"/>
</FrameLayout>
RecycleViewAdapter.java
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.CustomViewHolder> {
private Context context;
private List<String> stringList;
public RecycleViewAdapter(Context context, List<String> stringList) {
this.context = context;
this.stringList = stringList;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new CustomViewHolder(LayoutInflater.from(context).inflate(R.layout.recycle_item_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
holder.textView.setText(stringList.get(position));
}
#Override
public int getItemCount() {
return stringList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public CustomViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text);
}
}
}
recycle_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="8dp">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:background="#android:color/holo_blue_dark"
android:textColor="#android:color/white"
android:textSize="24sp" />
</LinearLayout>
Above code will give you following result -
Happy Coding !
I am new to programming in androidstudio/java so I'm looking for some assistance. I'm currently trying to make an app that is similar to facebook messenger by using firebase and android studio. I'm at the stage where I am trying to create the layout for the ChatActivity (see code below). However, I'm having some issues with showing new messages at the bottom of the screen.
I have tried using ".setStackFromEnd(true);" but setting it either true or false, the text still appears at the top! (see images)
Code:
ChatActivity is as follows:
public class ChatActivity extends AppCompatActivity {
//Firebase variables
private FirebaseAuth mAuth;
private DatabaseReference mDatabaseUser, mDatabaseChat;
private FirebaseStorage mStorage;
private StorageReference mStorageReference;
//Recyclerview variables
private RecyclerView recyclerView;
private RecyclerViewChatAdapter mChatAdapter;
//Variables for users
private String userId,friendId,namefriend,chatId;
private CircleImageView mImageFriend;
private ArrayList<ChatObject> resultsChat = new ArrayList<>();
private Button mSendButton;
private EditText mSendText;
private TextView mNameFriend;
//Linear layout manager
private LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
//prevent opening keyboard automatically
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//Set firebase variables
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
friendId = getIntent().getExtras().getString("friendId");
namefriend = getIntent().getExtras().getString("friendName");
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Friends").child(userId).child("Friendlist").child(friendId).child("chatId");
mDatabaseChat = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance();
mStorageReference = mStorage.getReference();
//Get findviewbyId's
recyclerView = (RecyclerView) findViewById(R.id.ChatActivity_recyclerview);
mSendButton = (Button) findViewById(R.id.ChatActivity_Send);
mSendText = (EditText) findViewById(R.id.ChatActivity_SendText);
mNameFriend = (TextView) findViewById(R.id.ChatActivity_Name);
mImageFriend = (CircleImageView) findViewById(R.id.ChatActivity_ImageFriend);
//Filling in recyclerview and adapter
FillInRecyclerView();
//Set name
mNameFriend.setText(" "+namefriend);
//set picture
StorageReference profileRef = mStorageReference.child("profilepictures/"+friendId);
GlideApp.with(this)
.load(profileRef)
.into(mImageFriend);
//Setting database for messages
getChatId();
//Send message
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
private void sendMessage() {
String sendMessageText = mSendText.getText().toString();
if(!sendMessageText.isEmpty()){
DatabaseReference newMessageDb = mDatabaseChat.push();
Map newMessage = new HashMap();
newMessage.put("createdByUser", userId);
newMessage.put("text", sendMessageText);
newMessageDb.setValue(newMessage);
}
mSendText.setText(null);
}
private void getChatId(){
mDatabaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
chatId = dataSnapshot.getValue().toString();
mDatabaseChat = mDatabaseChat.child("Message").child(chatId);
getChatMessages();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getChatMessages() {
mDatabaseChat.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if(dataSnapshot.exists()){
String message = null;
String createdByUser = null;
if (dataSnapshot.child("text").getValue()!=null){
message = dataSnapshot.child("text").getValue().toString();
}
if (dataSnapshot.child("createdByUser").getValue()!=null){
createdByUser = dataSnapshot.child("createdByUser").getValue().toString();
}
if(message!=null && createdByUser!=null){
Boolean currentUserBoolean = false;
if(createdByUser.equals(userId)){
currentUserBoolean=true;
}
ChatObject newMessage = new ChatObject(message, currentUserBoolean, createdByUser);
resultsChat.add(0,newMessage);
mChatAdapter.notifyDataSetChanged();
mLayoutManager.scrollToPositionWithOffset(0,0);
}
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void FillInRecyclerView(){
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mLayoutManager.scrollToPositionWithOffset(0,0);
mChatAdapter = new RecyclerViewChatAdapter(ChatActivity.this, resultsChat);
recyclerView.setAdapter(mChatAdapter);
recyclerView.setLayoutManager(mLayoutManager);
}
ActivityChat XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatActivity">
<LinearLayout
android:id="#+id/ChatActivity_LinearLayoutHeader"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/background_chatheader"
android:paddingStart="7dp"
android:paddingLeft="7dp"
android:windowSoftInputMode="adjustResize"
android:layout_marginBottom="3dp">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="45dp"
android:layout_height="45dp"
android:id="#+id/ChatActivity_ImageFriend"
android:src="#mipmap/ic_launcher"
android:layout_gravity="center"
/>
<TextView
android:id="#+id/ChatActivity_Name"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Test"
android:gravity="center_vertical|start"
android:textSize="25sp"
android:textColor="#color/white"
android:fontFamily="sans-serif"
/>
</LinearLayout>
<android.support.v4.widget.NestedScrollView
android:layout_below="#+id/ChatActivity_LinearLayoutHeader"
android:layout_above="#id/ChatActivity_LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="never"
android:scrollbarStyle="outsideOverlay"
>
<android.support.v7.widget.RecyclerView
app:stackFromEnd="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/ChatActivity_LinearLayout"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
android:id="#+id/ChatActivity_recyclerview"
>
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.NestedScrollView>
<LinearLayout
android:id="#+id/ChatActivity_LinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:layout_weight="0.7"
android:id="#+id/ChatActivity_SendText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Type your message..."
/>
<Button
android:layout_weight="0.3"
android:id="#+id/ChatActivity_Send"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="send"/>
</LinearLayout>
</RelativeLayout>
Itemlayout xml file for the recyclerview:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Recyclerview_Parent_Container"
>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/Recyclerview_ChatImage"
android:layout_width="42dp"
android:layout_height="42dp"
android:src="#mipmap/ic_launcher"
android:visibility="invisible"
/>
<LinearLayout
android:layout_marginStart="9dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6sp"
android:id="#+id/Recyclerview_Container"
android:orientation="horizontal"
android:background="#drawable/border_chat_bubbles"
android:layout_marginLeft="7dp"
android:layout_marginEnd="7dp">
<TextView
android:id="#+id/Recyclerview_Message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text"
android:textSize="18sp"
/>
</LinearLayout>
</LinearLayout>
RecyclerView adapter code:
public class RecyclerViewChatAdapter extends RecyclerView.Adapter<RecyclerViewChatAdapter.ViewHolder> {
private List<ChatObject> chatList;
private Context context;
//Firebase
private FirebaseAuth mAuth;
private String CurrentUserId;
private FirebaseStorage mStorage;
private StorageReference mStorageReference;
public RecyclerViewChatAdapter(Context context, List<ChatObject> chatList) {
this.chatList = chatList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_chatlist_layout, viewGroup, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
//Firebase variables
mStorage = FirebaseStorage.getInstance();
mStorageReference = mStorage.getReference();
mAuth = FirebaseAuth.getInstance();
CurrentUserId = mAuth.getCurrentUser().getUid();
//Setting profile picture into recyclerview
StorageReference profileRef = mStorageReference.child("profilepictures/" + chatList.get(position).getUserid());
GlideApp.with(context)
.load(profileRef)
.into(holder.mProfilepicture);
//Setting message layout for user and friend
holder.mMessage.setText(chatList.get(position).getMessage());
if (chatList.get(position).getCurrentUser()) {
holder.mParentContainer.setGravity(Gravity.END);
holder.mMessage.setTextColor(Color.parseColor("#404040"));
holder.mContainer.setBackgroundResource(R.drawable.border_chat_bubbles);
holder.mProfilepicture.setVisibility(View.INVISIBLE);
} else {
holder.mParentContainer.setGravity(Gravity.START);
holder.mMessage.setTextColor(Color.parseColor("#FFFFFF"));
holder.mContainer.setBackgroundResource(R.drawable.border_chat_bubbles_friend);
holder.mProfilepicture.setVisibility(View.VISIBLE);
//Set picture of friend when multiple messages
int i = 1;
if(position+i<chatList.size()) {
while (!chatList.get(position + i).getCurrentUser()) {
if ((chatList.get(position + i).getCurrentUser()) == chatList.get(position).getCurrentUser()) {
holder.mProfilepicture.setVisibility(View.INVISIBLE);
i++;
} else {
break;
}
if (position + i == chatList.size()) {
break;
}
}
}
}
}
#Override
public int getItemCount() {
return this.chatList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mMessage;
LinearLayout mContainer, mParentContainer;
CircleImageView mProfilepicture;
public ViewHolder(View itemView) {
super(itemView);
mParentContainer = itemView.findViewById(R.id.Recyclerview_Parent_Container);
mMessage = itemView.findViewById(R.id.Recyclerview_Message);
mContainer = itemView.findViewById(R.id.Recyclerview_Container);
mProfilepicture = itemView.findViewById(R.id.Recyclerview_ChatImage);
}
}
What it looks like on the emulator:
Screenshot of emulator of what it looks like
What I want it to look like:
Emulator of what I want
Now if I set SetStackFromEnd to true or false, I keep getting the same result as in the above picture. However, SetReverseLayout does work! What also does not work is the scrollToPositionWithOffset(0,0); or any other variation, I think the issue must be linked to each other
What have I tried to do already and did not work:
changing the position at what time "FillInRecyclerView()" method is being called, however this did not change anything.
Various combinations of SetReverseLayout/SetStackFromEnd to true
Setting stackfromend to true in the XML code
Changing the RelativeLayout to a LinearLayout in 'ChatActivity.xml'
Setting the relative layout height to match parent
Any help is welcome!
Thank you
You need to use both setStackFromEnd and setReverseLayout. Set both value true and you will get your expected output.
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(mContext);
recyclerView.setLayoutManager(mLinearLayoutManager);
mLinearLayoutManager.setStackFromEnd(true);
mLinearLayoutManager.setReverseLayout(true);
I want to make my homepage with two row with recyclerview
with data of books and the events which are display independent of each other how can i accomplish it I want to add event to the my code how can i do it?
MoviesAdapter.java
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
private List<Movie> moviesList;
public Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
thumbnail = (ImageView) view.findViewById(R.id.book);
}
}//End of MyViewHolder class
public MoviesAdapter(List<Movie> moviesList) {
this.moviesList = moviesList;
}
//display different items in the data set
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_list_row, parent, false);
return new MyViewHolder(itemView);
}
//display data at specified location
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.title.setText(moviesList.get(position).getTitle());
holder.thumbnail.setImageResource(moviesList.get(position).getImage());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
I want to make my page like this
It should be fine to use a LinearLayout with 3 RecyclerViews in it and create an Adapter for each of them. Nested RecyclerViews would only make sense if you had a lot of categories.
I done it with the three recyclerview and their adapter class here is the code of only MainActivity.java and activity.xml
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<Book> bookList = new ArrayList<>();
private List<Author> authorList = new ArrayList<>();
private List<Event> eventList = new ArrayList<>();
private RecyclerView recyclerView1;
private RecyclerView recyclerView2;
private RecyclerView recyclerView3;
private BookAdapter bAdapter;
private AuthorAdapter aAdapter;
private EventAdapter eAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView1 = findViewById(R.id.recycler_book);
bAdapter = new BookAdapter(this,bookList);
recyclerView1.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView1.setLayoutManager(mLayoutManager);
recyclerView1.setAdapter(bAdapter);
prepareBookData();
//second recycler
recyclerView2 = findViewById(R.id.recycler_author);
aAdapter = new AuthorAdapter(this,authorList);
recyclerView2.setHasFixedSize(true);
RecyclerView.LayoutManager aLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView2.setLayoutManager(aLayoutManager);
recyclerView2.setAdapter(aAdapter);
prepareAuthorData();
//third recycler
recyclerView3 = (RecyclerView) findViewById(R.id.recycler_event);
eAdapter = new EventAdapter(this,eventList);
recyclerView3.setHasFixedSize(true);
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
// RecyclerView.LayoutManager eLayoutManager = new GridLayoutManager(this,1,GridLayoutManager.HORIZONTAL,false);
recyclerView3.setLayoutManager(eLayoutManager);
recyclerView3.setAdapter(eAdapter);
prepareEventData();
}
private void prepareBookData(){
int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
String[] nameArray = {"You Can Win", "Half Girlfriend"};
Book a=new Book(nameArray[0],drawableArray[0]);
bookList.add(a);
Book b=new Book(nameArray[1],drawableArray[1]);
bookList.add(b);
Book c=new Book(nameArray[0],drawableArray[0]);
bookList.add(c);
bAdapter.notifyDataSetChanged();
}
private void prepareAuthorData(){
int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
String[] nameArray = {"You Can Win", "Half Girlfriend"};
Author a=new Author(nameArray[0],drawableArray[0]);
authorList.add(a);
Author b=new Author(nameArray[1],drawableArray[1]);
authorList.add(b);
Author c=new Author(nameArray[0],drawableArray[0]);
authorList.add(c);
Author d=new Author(nameArray[1],drawableArray[1]);
authorList.add(d);
bAdapter.notifyDataSetChanged();
}
private void prepareEventData(){
String[] desArray = {"new","old"};
String[] nameArray = {"You Can Win", "Half Girlfriend"};
Event a=new Event(nameArray[0],desArray[0]);
eventList.add(a);
Event b=new Event(nameArray[0],desArray[0]);
eventList.add(b);
Event c=new Event(nameArray[0],desArray[0]);
eventList.add(c);
bAdapter.notifyDataSetChanged();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:context="com.example.hardik.threerecycler.MainActivity"
android:background="#e6edec">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
app:cardCornerRadius="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Books"
android:textSize="20sp"
android:textStyle="bold" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_book"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginTop="20dp" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Authors"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginTop="10dp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_author"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/recycler_book"
android:layout_marginTop="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Events"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginTop="10dp"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_event"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/recycler_author"
android:layout_marginTop="5dp"/>
</LinearLayout>
I tried to implement an onClick method to my card recyclerView. When I click the card nothing happens but when I click the gap between the cards the intended action is performed. This was confirmed when as I tested this by increasing the spacing between the cards. What did I do wrong and how do I change my code to fix this problem?
This is the Adapter
public class JobListRecyclerAdapter extends RecyclerView.Adapter<JobListRecyclerAdapter.jobViewHolder> {
private ArrayList<JobClass> jobClassList;
private static OnItemClickListener clickListener;
public JobListRecyclerAdapter(ArrayList<JobClass> rList) {
this.jobClassList = rList;
}
#Override
public int getItemCount() {
if(jobClassList == null){return 0;}
return jobClassList.size();
}
#Override
public jobViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.job_list_card, viewGroup, false);
return new jobViewHolder(itemView);
}
#Override
public void onBindViewHolder(jobViewHolder jobViewHolder, int position) {
JobClass ci = jobClassList.get(position);
jobViewHolder.jName.setText("Name: "+ci.getmJobNum());
jobViewHolder.jDate.setText("Quantity: "+ci.getmJobDate());
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
public static class jobViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView jName;
protected TextView jDate;;
public jobViewHolder(View j) {
super(j);
jName = (TextView) j.findViewById(R.id.job_name);
jDate = (TextView) j.findViewById(R.id.job_due_date);
itemView.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
}
#Override
public void onClick(View view) {
if (clickListener != null) {clickListener.onClick(view, getLayoutPosition());}
}
}
}
This is the Activity
public class JobList extends Fragment implements OnItemClickListener {
public JobList() {
}
public static JobList newInstance() {
JobList fragment = new JobList();
return fragment;
}
#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_job_list, container, false);
final RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.job_list_recycler_view);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(llm);
final ArrayList<JobClass> joblistclass = new ArrayList<>();
/*
// Create a new Adapter
final ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1);
*/
// Get a reference to the todoItems child items it the database
//String userPath = ((GlobalData) getActivity().getApplication()).getUserPath() +"JOBS";
//final DatabaseReference myRef = database.getReference(userPath);
// final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("USERS/04950F4AE53F80/JOBS");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference jobsRef = rootRef
.child("USERS")
.child("04950F4AE53F80")
.child("JOBS");
// Assign a listener to detect changes to the child items
// of the database reference.
// myRef.addValueEventListener(new ValueEventListener() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String jobno = ds.child("JOBOVERVIEW").child("jobNum").getValue(String.class);
JobClass jblst = ds.child("JOBOVERVIEW").getValue(JobClass.class);
joblistclass.add(jblst);
((GlobalData) getContext().getApplicationContext()).saveJobNum(jobno);
}
final JobListRecyclerAdapter adapterb = new JobListRecyclerAdapter(joblistclass);
recyclerView.setAdapter(adapterb);
adapterb.setClickListener(JobList.this);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
jobsRef.addListenerForSingleValueEvent(eventListener);
///to send to next page
Button nextPage = (Button) rootView.findViewById(R.id.addNewJob);
// Capture button clicks
nextPage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start NewActivity.class
Intent myIntent = new Intent(getContext(), JobForm.class);
startActivity(myIntent);
}
});
return rootView;
}
#Override
public void onClick(View view, int position) {
ArrayList<String> nameArray = ((GlobalData) getActivity().getApplication()).getJobNums();
String name = nameArray.get(position);
((GlobalData) getActivity().getApplication()).setJobId(name);
Toast.makeText(getContext(), name,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(getContext(), Main2Activity.class);
startActivity(intent);
}
}
Card View XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardUseCompatPadding="true"
android:id="#+id/job_card_layout"
android:layout_marginBottom="4dp"
android:clickable="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:id="#+id/job_linear_layout"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="9dp"
android:clickable="true"
>
<TextView
android:id="#+id/job_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:clickable="true"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/job_due_date"
android:layout_toRightOf="#+id/job_name"
android:clickable="true"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
Please use below xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView android:id="#+id/job_card_layout"
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="wrap_content"
android:layout_marginBottom="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:id="#+id/job_linear_layout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginBottom="9dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/job_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textSize="20sp" />
<TextView
android:id="#+id/job_due_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/job_name" />
</LinearLayout>
Note: android:clickable="true" has to be removed from your xml file.
Also, use
j.setOnClickListener(this);
instead of
itemView.setOnClickListener(this);
You don't have itemView field in your adapter or viewHolder as I can see. Maybe jobViewHolder should look like this:
jName = (TextView) j.findViewById(R.id.job_name);
jDate = (TextView) j.findViewById(R.id.job_due_date);
j.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
Maybe your child view is placed at foreground and take all interactive from user. Let try this code in your child view xml.
android:duplicateParentState="true"
Update jobViewHolder class
Change following line
itemView.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
to
j.findViewById(R.id.job_card_layout).setOnClickListener(this); // bind the listener
OR
j.setOnClickListener(this); // bind the listener
NOTE: If this doesn't work then you are referring wrong id i.e. job_card_layout
Updated JobViewHolder.java
public static class jobViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView jName;
protected TextView jDate;;
public jobViewHolder(View j) {
super(j);
jName = (TextView) j.findViewById(R.id.job_name);
jDate = (TextView) j.findViewById(R.id.job_due_date);
itemView.setOnClickListener(this); // bind the listener
}
#Override
public void onClick(View view) {
if (clickListener != null) {clickListener.onClick(view, getLayoutPosition());}
}
}
I am getting data from TMDB API and displaying it on screen.
Right now, I am trying to get reviews from that API.
Everything seems fine, I created: adapter,model,interface,xml and activities, but it is not displaying any data.
API is working fine, I can see from Android Monitor that I am getting right data.
Somebody help, please.
Bellow is my DetailsActivity where I am trying to fetch data:
public class MovieDetailActivity extends AppCompatActivity {
public static final String EXTRA_MOVIE = "EXTRA_MOVIE";
private Movie mMovie;
private Reviews mReviews;
private Genres mGenres;
public ReviewAdapter rAdapter;
ImageView backdrop;
ImageView poster;
TextView title;
TextView description;
TextView releaseDate;
TextView voteAverage;
RecyclerView reviews;
TextView content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_detail);
if (getIntent().hasExtra(EXTRA_MOVIE)) {
mMovie = getIntent().getParcelableExtra(EXTRA_MOVIE);
} else {
throw new IllegalArgumentException("Detail activity must receive a movie parcelable");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
toolbarLayout.setTitle(mMovie.getTitle());
reviews = (RecyclerView) findViewById(R.id.recyclerView2);
reviews.setLayoutManager(new LinearLayoutManager(this));
rAdapter = new ReviewAdapter(MovieDetailActivity.this);
reviews.setAdapter(rAdapter);
getReviews(mMovie.getId());
poster = (ImageView) findViewById(R.id.movie_poster);
String internetUrl = "http://image.tmdb.org/t/p/w500";
Glide.with(this)
.load(mMovie.getPoster())
.into(poster);
Glide.with(this)
.load(mMovie.getBackdrop())
.into(backdrop);
}
private void getReviews(Integer id) {
RestAdapter.getMovieService().getReviews(id, new Callback<ReviewWraper>() {
#Override
public void success(ReviewWraper reviewWraper, Response response) {
rAdapter.setReviewList(reviewWraper.getResults());
}
#Override
public void failure(RetrofitError error) {
error.printStackTrace();
}
});
}
public static class MovieViewHolder extends RecyclerView.ViewHolder {
public ImageView reviewPicture;
public TextView reviewUsername;
public TextView reviewDate;
public TextView reviewTime;
public TextView reviewComment;
public MovieViewHolder(View itemView) {
super(itemView);
reviewPicture = (ImageView) itemView.findViewById(R.id.picture_review);
reviewUsername = (TextView) itemView.findViewById(R.id.username_review);
reviewDate = (TextView) itemView.findViewById(R.id.date_review);
reviewTime = (TextView) itemView.findViewById(R.id.time_review);
reviewComment = (TextView) itemView.findViewById(R.id.review_comment);
}
}
Here is my adapter class:
public class ReviewAdapter extends RecyclerView.Adapter<MovieDetailActivity.MovieViewHolder> {
private List<Reviews> rReviewList;
private LayoutInflater rInflater;
private Context rContext;
public ReviewAdapter(Context context) {
this.rContext = context;
this.rInflater = LayoutInflater.from(context);
this.rReviewList = new ArrayList<>();
}
public MovieDetailActivity.MovieViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
// create a new view
View view = rInflater.inflate(R.layout.row_review, parent, false);
return new MovieDetailActivity.MovieViewHolder(view);
}
#Override
public void onBindViewHolder(MovieDetailActivity.MovieViewHolder holder, int position) {
Reviews reviews = rReviewList.get(position);
Picasso.with(rContext)
.load(reviews.getUrl())
.into(holder.reviewPicture);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Perform click
}
});
}
#Override
public int getItemCount() {
return rReviewList.size();
}
//To update data
public void setReviewList(List<Reviews> reviewsList) {
this.rReviewList = new ArrayList<>();
this.rReviewList.addAll(reviewsList);
notifyDataSetChanged();
}
Bellow is XML 1:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/picture_review"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:adjustViewBounds="true"
android:id="#+id/username_review"
android:layout_width="40dp"
android:layout_height="20dp"
android:width="20dp"
android:height="20dp"
android:textColor="#ffffff" />
<TextView
android:id="#+id/date_review"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textColor="#ffffff" />
<TextView
android:id="#+id/time_review"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ffffff" />
<TextView
android:id="#+id/review_comment"
android:layout_width="250dp"
android:layout_height="250dp"
android:textColor="#ffffff"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/picture_review"
android:layout_toEndOf="#+id/picture_review" />
</RelativeLayout>
And XML 2 with RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.demo.mtin.mtin.MovieDetailActivity"
tools:showIn="#layout/activity_movie_detail">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ffffff" />
Try to give fixed height instead of "wrap_content" on your row in root of Xml 1.
tools:showIn="#layout/activity_movie_detail">
If XML 2 needs to show in XML 1, XML1 must have this -
<include layout="#layout/XML2"/>
See this for more details -
android-how-to-use-tools-with-include-layout