I'm trying to display my ViewPager since few times without success.
In fact, my fragment layout (which contains the ViewPager) is cut in two parts with weight.
When I check the preview of the Adapter, I see what I want, which is not the case when the application is launched.
This is the code of my Fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_search, container, false);
if (this.getArguments().getString("search") != null) {
final List<Produit> produitList =
HypredDbManager.getDbManager().getProduitDbManager()
.getProduitsByString(this.getArguments().getString("search"));
String product = Integer.toString(produitList.size()) + " ";
if (produitList.size() > 1) {
product += getResources().getString(R.string.products);
} else {
product += getResources().getString(R.string.product);
}
((TextView) rootView.findViewById(R.id.search_nombre_produits)).setText(product);
ArrayList<View> viewArrayList = new ArrayList<>();
for (int i = 0; i < produitList.size(); i++) {
ProduitItem produitItem = new ProduitItem(rootView.getContext(), produitList.get(i));
produitItem.setProduitItemListener(new ProduitItem.produitItemListener() {
#Override
public void onProduitSelected(Produit produit) {
mCallback.changeFragment(produit);
}
#Override
public void ajoutPanier(Produit produit) {
SelectionManager.getInstance().addProductToSelection(rootView.getContext(), ProduitSelectionne.fromProduitAndHistorique(produit, ""));
}
});
viewArrayList.add(produitItem);
}
HypredTableLayout hypredTableLayout = (HypredTableLayout) rootView.findViewById(R.id.search_tablelayout_produit);
hypredTableLayout.addChild(viewArrayList, 2, this);
final ArrayList<Protocole> protocoles = new ArrayList<>();
protocoles.addAll(HypredDbManager.getDbManager().getProtocoleDbManager()
.getProtocolesByString(this.getArguments().getString("search")));
String protocole = Integer.toString(protocoles.size()) + " ";
if (protocoles.size() > 1) {
protocole += getResources().getString(R.string.protocoles);
} else {
protocole += getResources().getString(R.string.protocole);
}
((TextView) rootView.findViewById(R.id.search_nombre_protocoles)).setText(protocole);
Log.d(TAG, "protocoles : " + protocoles.size());
if(protocoles.size()> 0) {
ViewPager viewPagerProtocole = (ViewPager) rootView.findViewById(R.id.search_viewpager_protocole);
ProtocoleAdapterViewPager protocoleAdapterViewPager = new ProtocoleAdapterViewPager(rootView.getContext(), protocoles);
protocoleAdapterViewPager.setClickOnProductListener(new ProtocoleAdapterViewPager.clickOnProductListener() {
#Override
public void appelProduit(long productId) {
mCallback.changeFragment(HypredDbManager.getDbManager().getProduitDbManager().getProduitById(productId));
}
#Override
public void ajouterAllProduit(ArrayList<Produit> produitArrayList) {
for (int i = 0; i < produitArrayList.size(); i++) {
SelectionManager.getInstance().addProductToSelection(getActivity(), ProduitSelectionne.fromProduitAndHistorique(produitArrayList.get(i), ""));
}
}
#Override
public void ajouterProduit(Produit produit) {
SelectionManager.getInstance().addProductToSelection(getActivity(), ProduitSelectionne.fromProduitAndHistorique(produit, ""));
}
});
viewPagerProtocole.setAdapter(protocoleAdapterViewPager);
viewPagerProtocole.setCurrentItem(0);
Log.d(TAG, "protocoleAdapterViewPager : " + protocoleAdapterViewPager.getCount());
Log.d(TAG, "getcurrentitem : " + viewPagerProtocole.getCurrentItem());
}
}
return rootView;
}
The getCount of my Adapter return the right size.
The xml of my Fragment :
<?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="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
android:weightSum="10">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="10sp"
android:layout_marginTop="10sp"
android:layout_weight="5"
android:background="#drawable/border_process_organe_right"
android:gravity="center_horizontal"
android:orientation="vertical">
<com.ylly.hypred.custom.MyTextView
android:id="#+id/search_nombre_produits"
style="#style/HypredTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:layout_marginRight="5sp"
android:layout_marginTop="10sp"
android:gravity="center_horizontal"
android:textColor="#color/hypred_rouge" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp">
<com.ylly.hypred.custom.HypredTableLayout
android:id="#+id/search_tablelayout_produit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="#null" />
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="5"
android:background="#color/hypred_vert"
android:gravity="center_horizontal"
android:orientation="horizontal">
<com.ylly.hypred.custom.MyTextView
android:id="#+id/search_nombre_protocoles"
style="#style/HypredTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:layout_marginRight="5sp"
android:layout_marginTop="10sp"
android:gravity="center_horizontal"
android:textColor="#color/hypred_rouge" />
<android.support.v4.view.ViewPager
android:id="#+id/search_viewpager_protocole"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/hypred_rouge" />
</LinearLayout>
</LinearLayout>
The code of my Adapter :
package com.ylly.hypred.search.adapters;
import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ylly.hypred.R;
import com.ylly.hypred.dao.Etape;
import com.ylly.hypred.dao.Produit;
import com.ylly.hypred.dao.Protocole;
import com.ylly.hypred.db.HypredDbManager;
import com.ylly.hypred.process.adapter.AdapterEtape;
import com.ylly.hypred.process.recyclerView.SpacesItemDecoration;
import org.solovyev.android.views.llm.LinearLayoutManager;
import java.util.ArrayList;
/**
* Created by YLLY on 06-10-2015.
*/
public class ProtocoleAdapterViewPager extends PagerAdapter {
private ArrayList<Protocole> protocoleArrayList;
private clickOnProductListener mCallback;
private Context context;
private LayoutInflater inflater;
public interface clickOnProductListener {
void appelProduit(long productId);
void ajouterAllProduit(ArrayList<Produit> produitArrayList);
void ajouterProduit(Produit produit);
}
public ProtocoleAdapterViewPager(Context context, ArrayList<Protocole> protocoles) {
this.protocoleArrayList = new ArrayList<>();
protocoleArrayList.addAll(protocoles);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.protocoleArrayList.size();
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
View root = inflater.inflate(R.layout.viewpager_search_container, null);
FrameLayout frameLayout = (FrameLayout) root.findViewById(R.id.viewpager_search_container_container);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.adapter_view_pager_protocole, null);
TextView labelProtocoleTextView = (TextView) linearLayout.findViewById(R.id.adapter_view_pager_protocole_label_text_view);
RecyclerView produitsRecyclerView = (RecyclerView) linearLayout.findViewById(R.id.adapter_view_pager_protocole_recycler_view);
ImageView imageViewPanierSelectionAll = (ImageView) linearLayout.findViewById(R.id.adapter_view_pager_protocole_panier_rouge);
labelProtocoleTextView.setText(protocoleArrayList.get(position).getName());
produitsRecyclerView.addItemDecoration(new SpacesItemDecoration(0, 0, 0, 10));
produitsRecyclerView.setLayoutManager(new LinearLayoutManager(root.getContext(), LinearLayoutManager.VERTICAL, false));
final ArrayList<Etape> fEtapeArrayList = new ArrayList<>();
if(protocoleArrayList.get(position).getEtapeId()!= null) {
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeId()));
}
}
if(protocoleArrayList.get(position).getEtapeTwoId()!= null) {
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeTwoId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeTwoId()));
}
}
if(protocoleArrayList.get(position).getEtapeThreeId()!= null) {
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeThreeId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeThreeId()));
}
}
if(protocoleArrayList.get(position).getEtapeFourId()!= null) {
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFourId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFourId()));
}
}
if(protocoleArrayList.get(position).getEtapeFiveId()!= null) {
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFiveId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFiveId()));
}
}
if(protocoleArrayList.get(position).getEtapeSixId()!= null) {
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeSixId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeSixId()));
}
}
final AdapterEtape etapeAdapter = new AdapterEtape(fEtapeArrayList, root.getContext());
etapeAdapter.setClickOnProductListener(new AdapterEtape.clickOnProductListener() {
#Override
public void appelerProduit(long produitId) {
mCallback.appelProduit(produitId);
}
#Override
public void ajouterProduitSelection(Produit produit) {
mCallback.ajouterProduit(produit);
}
});
produitsRecyclerView.setAdapter(etapeAdapter);
imageViewPanierSelectionAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Produit> produits = new ArrayList<>();
for (int i = 0; i < fEtapeArrayList.size(); i++) {
produits.add((fEtapeArrayList.get(i).getProduit()));
}
mCallback.ajouterAllProduit(produits);
}
});
frameLayout.addView(linearLayout);
collection.addView(root);
return root;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == (View) object;
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
public void setClickOnProductListener(clickOnProductListener callback) {
mCallback = callback;
}
}
And his xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto" android:orientation="vertical"
android:background="#color/hypred_rouge"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#drawable/border_process_protocole_title">
<com.ylly.hypred.custom.MyTextView
android:id="#+id/adapter_view_pager_protocole_label_text_view"
android:layout_width="wrap_content"
custom:font_name="Arial-Bold.ttf"
android:textSize="20sp"
android:textColor="#color/hypred_blanc"
android:gravity="center"
android:layout_height="wrap_content" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:overScrollMode="never">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/border_process_protocole_corps">
<android.support.v7.widget.RecyclerView
android:layout_marginTop="15dp"
android:id="#+id/adapter_view_pager_protocole_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:scrollbarStyle="insideOverlay"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:overScrollMode="never">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="10">
<com.ylly.hypred.custom.MyTextView
android:text="#string/selection_produits"
android:textColor="#color/hypred_noir"
android:layout_width="0dp"
android:layout_weight="7"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"/>
<ImageView
android:id="#+id/adapter_view_pager_protocole_panier_rouge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:layout_marginBottom="5dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:src="#drawable/hypred_protocole_panier_rouge"/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
</LinearLayout>
I'm sure it's just a stupid mistake but I don't see it >:
Thanks in advance and have a good day !
Check this:
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="5"
android:background="#color/hypred_vert"
android:gravity="center_horizontal"
android:orientation="horizontal">
<com.ylly.hypred.custom.MyTextView
android:id="#+id/search_nombre_protocoles"
style="#style/HypredTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:layout_marginRight="5sp"
android:layout_marginTop="10sp"
android:gravity="center_horizontal"
android:textColor="#color/hypred_rouge" />
<android.support.v4.view.ViewPager
android:id="#+id/search_viewpager_protocole"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/hypred_rouge" />
</LinearLayout>
In this LinearLayout you have android:orientation="horizontal", but you set to your TextView android:layout_width="match_parent". So, in this case your TextView fill out all LinearLayout and there no free space for your ViewPager.
It seems, that's the reason why ViewPager doesn't appear.
Maybe LinearLayout orientation should be vertical.
Related
When TextView containing chat message is having content more than accommodatable in one line, the text view stops listening for clicks and long clicks. I tried to listen same events on the parent item of TextView, but it's not working there as well.
This is the code:
<TextView
android:id="#+id/message_text_view"
android:background="#drawable/bubble_right"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/open_sans"
android:layout_marginStart="17dp"
android:layout_marginEnd="5dp"
android:paddingTop="8sp"
android:paddingBottom="8sp"
android:paddingStart="20sp"
android:paddingEnd="20sp"
android:text="#string/hello"
android:textColor="#color/white"
android:textSize="16sp" />
Java code:
messageRightBinding.messageTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
messageRightBinding.messageTextView.setVisibility(View.VISIBLE);
return true;
}
});
Full XML layout file:
<?xml version="1.0" encoding="utf-8"?>
<layout
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"
tools:context=".ChatActivity">
<data>
<import type="android.view.View"/>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/conversation_time"
android:visibility="gone"
android:layout_margin="20sp"
android:textSize="14sp"
android:layout_gravity="center"
android:gravity="center"
android:textAlignment="center"
android:text="2 July, 2018"
android:textColor="#color/light_black"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="end|center_vertical"
android:padding="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end|center_vertical"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
android:id="#+id/message_holder">
<TextView
android:id="#+id/message_text_view"
android:background="#drawable/bubble_right"
android:clickable="false"
android:focusable="false"
android:longClickable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/open_sans"
android:layout_marginStart="17dp"
android:layout_marginEnd="5dp"
android:paddingTop="8sp"
android:paddingBottom="8sp"
android:paddingStart="20sp"
android:paddingEnd="20sp"
android:text="#string/hello"
android:textColor="#color/white"
android:textSize="16sp" />
</RelativeLayout>
<LinearLayout
android:visibility="gone"
android:id="#+id/message_button_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:background="#drawable/rounded_whitebackground"
android:backgroundTint="#color/dark_pink"
android:id="#+id/unsend_button_right"
android:layout_width="90sp"
android:layout_height="40sp"
android:layout_marginEnd="5sp"
android:textColor="#color/white"
android:textSize="16sp"
android:fontFamily="#font/open_sans"
android:padding="6sp"
android:text="#string/unsend" />
<Button
android:background="#drawable/rounded_whitebackground"
android:backgroundTint="#color/dark_pink"
android:id="#+id/unsend_button_right_hide"
android:layout_width="30sp"
android:layout_height="40sp"
android:textColor="#color/white"
android:textSize="16sp"
android:padding="8sp"
android:fontFamily="#font/open_sans"
android:text="#string/x" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:clickable="false"
android:focusable="false"
android:gravity="center_vertical|end"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:clickable="true"
android:longClickable="true"
android:focusable="true"
android:id="#+id/time_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto"
android:text="#string/_11_00pm"
android:textColor="#color/light_black"
android:textSize="12sp" />
<ImageView
android:clickable="false"
android:focusable="false"
android:id="#+id/indicator_image_view"
android:layout_margin="2sp"
android:layout_width="12sp"
android:layout_height="12sp"
android:tint="#color/light_black"
app:srcCompat="#drawable/ic_check_black_24dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</layout>
Full RecyclerView code
package batteries;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.titanictek.titanicapp.R;
import com.titanictek.titanicapp.databinding.MessageLeftBinding;
import com.titanictek.titanicapp.databinding.MessageRightBinding;
import com.titanictek.titanicapp.db.AppDatabase;
import com.titanictek.titanicapp.db.Contacts;
import com.titanictek.titanicapp.db.DatabaseInstance;
import com.titanictek.titanicapp.db.NewMessage;
import com.titanictek.titanicapp.fragment.ChatFragment2;
import com.titanictek.titanicapp.services.WebSocketTypes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class ChatMessageRecyclerAdapter2 extends RecyclerView.Adapter{
Context context;
private UUID userId;
// private String threadId;
private Contacts contact;
private ArrayList<NewMessage> newMessages;
private static final int MESSAGE_SENT = 1;
private static final int MESSAGE_RECEIVED = 2;
final private RecyclerView recyclerView;
final ChatFragment2.OnSeenCallback onSeen;
public ChatMessageRecyclerAdapter2(Context context, UUID userId, String threadId, Contacts contact, RecyclerView recyclerView, ChatFragment2.OnSeenCallback onSeen) {
this.context = context;
this.userId = userId;
// this.threadId = threadId;
this.contact = contact;
this.recyclerView = recyclerView;
this.newMessages = new ArrayList<>();
this.onSeen = onSeen;
}
public void setContact(Contacts contact) {
this.contact = contact;
}
public void addMessagesFirst(List<NewMessage> messages) {
newMessages.addAll(0, messages);
// recyclerView.getLayoutManager().fi
notifyDataSetChanged();
recyclerView.scrollToPosition(messages.size()+5);
}
// todo: Add SCROLL logic
public void clearMessages() {
newMessages.clear();
notifyDataSetChanged();
scrollToBottom();
}
public void addMessagesInLast(List<NewMessage> messages) {
newMessages.addAll(messages);
notifyDataSetChanged();
scrollToBottom();
}
public void addMessage(NewMessage message) {
newMessages.add(message);
notifyDataSetChanged();
scrollToBottom();
}
public void onMessageSeen(ArrayList<String> messageIds) {
int c = messageIds.size();
for (NewMessage message: newMessages) {
if (messageIds.contains(message.getMessageId())) {
message.setReached(3);
c--;
if (c==0) break;
}
}
if (c < messageIds.size()) notifyDataSetChanged();
}
public void onMessageSent(WebSocketTypes.ChatMessageDeliveryStatus status) {
for (NewMessage message: newMessages) {
if (message.getMessageId().equals(status.refId.toString())) {
message.setReached(1);
message.setMessageId(status.messageId.toString());
notifyDataSetChanged();
break;
}
}
}
public void onMessageDelivered(String messageId) {
for (NewMessage message: newMessages) {
if (message.getMessageId().equals(messageId)) {
message.setReached(2);
notifyDataSetChanged();
break;
}
}
}
public void addMessagesInLast(NewMessage ...messages) {
final int oldSize = newMessages.size();
newMessages.addAll(Arrays.asList(messages));
// notifyDataSetChanged();
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffUtil.Callback() {
#Override
public int getOldListSize() {
return oldSize;
}
#Override
public int getNewListSize() {
return newMessages.size();
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return newItemPosition < oldSize;
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return newItemPosition < oldSize;
}
});
diffResult.dispatchUpdatesTo(this);
scrollToBottom();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == MESSAGE_SENT){
return new SendMessageHolder(MessageRightBinding.inflate(
LayoutInflater.from(context), parent, false)
);
} else {
return new ReceiveMessageHolder(MessageLeftBinding.inflate(
LayoutInflater.from(context), parent, false)
);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
NewMessage message = newMessages.get(position);
if(message.getUserId().equals(userId.toString())){
((SendMessageHolder) holder).bind(message, position);
} else {
if (!message.isSeen()) {
message.setReached(3);
onSeen.run(message);
}
((ReceiveMessageHolder) holder).bind(message, position);
}
}
public void scrollToBottom() {
if (getItemCount() > 0) {
Log.w("SCROLL", "DONE");
recyclerView.smoothScrollToPosition(getItemCount());
}
}
#Override
public int getItemViewType(int position) {
NewMessage newMessage = newMessages.get(position);
if (newMessage.getUserId().equals(userId.toString())) {
return MESSAGE_SENT;
} else {
return MESSAGE_RECEIVED;
}
}
private int getItemViewType(NewMessage newMessage) {
//Log.w("NewMessage SentBy", newMessage.getUserId());
//Log.w("NewMessage Received By", contacts.getId());
if (newMessage.getUserId().equals(userId.toString())) {
return MESSAGE_SENT;
} else {
return MESSAGE_RECEIVED;
}
}
#Override
public int getItemCount() {
return newMessages.size();
}
private class SendMessageHolder extends RecyclerView.ViewHolder{
private MessageRightBinding messageRightBinding;
SendMessageHolder(MessageRightBinding binding) {
super(binding.getRoot());
this.messageRightBinding = binding;
}
public void bind(NewMessage newMessage, int position){
// messageRightBinding.mes.setText(newMessage.getText());
messageRightBinding.messageTextView.setText(newMessage.getText());
/*Picasso.rest().load(contacts.getProfilePicture()).resize(50, 50).
into(messageRightBinding.messageRightPp);*/
if (newMessage.isSeen()) {
messageRightBinding.indicatorImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_eye_black_24dp));
} else {
if (newMessage.isSent())
messageRightBinding.indicatorImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_check_black_24dp));
else // if (newMessage.isSentFailed())
messageRightBinding.indicatorImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_access_time_black_24dp));
}
messageRightBinding.timeTextView.setText(ContentUtils.getTime(newMessage.getTime()));
long lastTime = 0;
messageRightBinding.conversationTime.setVisibility(View.GONE);
if (position != 0) {
lastTime = ChatMessageRecyclerAdapter2.this.newMessages.get(position - 1).getTime();
if (newMessage.getTime() - lastTime >= 20000000) {
messageRightBinding.conversationTime.setText(new Date(newMessage.getTime()).toString());
messageRightBinding.conversationTime.setVisibility(View.VISIBLE);
}
} else {
messageRightBinding.conversationTime.setText(new Date(newMessage.getTime()).toString());
messageRightBinding.conversationTime.setVisibility(View.VISIBLE);
}
messageRightBinding.messageButtonHolder.setVisibility(View.GONE);
messageRightBinding.messageHolder.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
messageRightBinding.messageButtonHolder.setVisibility(View.VISIBLE);
return true;
}
});
messageRightBinding.unsendButtonRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messageRightBinding.unsendButtonRight.removeCallbacks(null);
// newMessages.remove(position);
newMessages.remove(position);
notifyDataSetChanged(); // position -1, newMessages.size() - position );
Toast.makeText(context, "Unsending the message", Toast.LENGTH_SHORT).show();
}
});
messageRightBinding.unsendButtonRightHide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messageRightBinding.messageButtonHolder.setVisibility(View.GONE);
}
});
}
}
private class ReceiveMessageHolder extends RecyclerView.ViewHolder{
private MessageLeftBinding messageLeftBinding;
ReceiveMessageHolder(MessageLeftBinding binding) {
super(binding.getRoot());
this.messageLeftBinding = binding;
}
public void bind(NewMessage newMessage, int position){
messageLeftBinding.messageTextView.setText(newMessage.getText());
if (position +1 < ChatMessageRecyclerAdapter2.this.getItemCount() && contact != null)
if (ChatMessageRecyclerAdapter2.this.getItemViewType(position+1) != MESSAGE_RECEIVED)
{
Picasso.get().load(contact.getProfilePicture()).resize(50, 50).
into(messageLeftBinding.messageLeftPp);
messageLeftBinding.messageLeftPp.setVisibility(View.VISIBLE);
}
else
messageLeftBinding.messageLeftPp.setVisibility(View.VISIBLE);
else if(contact != null) {
Picasso.get().load(contact.getProfilePicture()).resize(50, 50).
into(messageLeftBinding.messageLeftPp);
messageLeftBinding.messageLeftPp.setVisibility(View.VISIBLE);
}
long lastTime = 0;
messageLeftBinding.conversationTime.setVisibility(View.GONE);
if (position != 0) {
lastTime = ChatMessageRecyclerAdapter2.this.newMessages.get(position - 1).getTime();
if (newMessage.getTime() - lastTime >= 20000000) {
messageLeftBinding.conversationTime.setText(new Date(newMessage.getTime()).toString());
messageLeftBinding.conversationTime.setVisibility(View.VISIBLE);
}
} else {
messageLeftBinding.conversationTime.setText(new Date(newMessage.getTime()).toString());
messageLeftBinding.conversationTime.setVisibility(View.VISIBLE);
}
messageLeftBinding.timeTextView.setText(ContentUtils.getTime(newMessage.getTime()));
}
}
}
Screenshot:
Here the Unsend and X button come on long click, but that works only for one liner messages.
Any help or suggestion will be appreciated and I will be very thankful.
try putting your text in a relativelayout and give the click listener to the relative layout
Set android:clickable="true" and android:longClickable="true" on your TextView.
In your SendMessageHolder class, replace
messageRightBinding.messageHolder.setOnLongClickListener
with
itemView.setOnLongClickListener
You shouldn't set a long-click listener on a child View in a RecyclerView.
Sorry everyone for wasting your time and frying your heads for a problem which was not there actually. Those two buttons "Unsend" and "X" were not visible because when the TextView got content in length more than a line, it's was using the full width of screen leaving no space for other things. Hence even when the button's state was visible the buttons were not there in view port. Causing this so lengthy discussion and a misleading question title.
Finally this worked for me:
<LinearLayout
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="end|center_vertical"
android:padding="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end|center_vertical"
android:orientation="horizontal"
android:id="#+id/message_holder"
android:clickable="true"
android:focusable="true"
android:longClickable="true">
<TextView
android:id="#+id/message_text_view"
android:background="#drawable/bubble_right"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/open_sans"
android:layout_marginStart="17dp"
android:layout_marginEnd="5dp"
android:paddingTop="8sp"
android:paddingBottom="8sp"
android:paddingStart="20sp"
android:paddingEnd="20sp"
android:text="#string/hello"
android:textColor="#color/white"
android:textSize="16sp"
android:layout_toStartOf="#id/message_button_holder"/>
<LinearLayout
android:visibility="gone"
android:id="#+id/message_button_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:background="#drawable/rounded_whitebackground"
android:backgroundTint="#color/dark_pink"
android:id="#+id/unsend_button_right"
android:layout_width="90sp"
android:layout_height="40sp"
android:layout_marginEnd="5sp"
android:textColor="#color/white"
android:textSize="16sp"
android:fontFamily="#font/open_sans"
android:padding="6sp"
android:text="#string/unsend" />
<Button
android:background="#drawable/rounded_whitebackground"
android:backgroundTint="#color/dark_pink"
android:id="#+id/unsend_button_right_hide"
android:layout_width="30sp"
android:layout_height="40sp"
android:textColor="#color/white"
android:textSize="16sp"
android:padding="8sp"
android:fontFamily="#font/open_sans"
android:text="#string/x" />
</LinearLayout>
</RelativeLayout>
Sorry to everyone once again.
I am using a listview with swipelayout (daimajia library) and my listview is scrolling...
My problem is when I swipe listview item and click on button in it ,it returns me wrong position..
Do you have any idea of how to solve this??
This is my adapter
public View generateView(final int position, final ViewGroup parent) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, null);
SwipeLayout swipeLayout = (SwipeLayout) v.findViewById(getSwipeLayoutResourceId(position));
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
}
});
swipeLayout.setOnDoubleClickListener(new
SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(context, "DoubleClick",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
I think your implementation of getView method is messy. Try this.
ListAdapter Java class.
package com.dev4solutions.myapplication.activities;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SimpleSwipeListener;
import com.daimajia.swipe.SwipeLayout;
import com.dev4solutions.myapplication.R;
import java.util.ArrayList;
class ListAdapter extends BaseAdapter {
private ArrayList<String> strings;
private Context mContext;
public ListAdapter(Context context, ArrayList<String> list) {
strings = list;
mContext = context;
}
#Override
public int getCount() {
return strings.size();
}
#Override
public Object getItem(int i) {
return strings.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.ledger_layout, null);
viewHolder = new ViewHolder();
viewHolder.swipeLayout = view.findViewById(R.id.swipe);
viewHolder.textView = view.findViewById(R.id.text_data);
viewHolder.delete = view.findViewById(R.id.delete);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.textView.setText(String.valueOf("Swipe Layout : " + position));
viewHolder.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
Toast.makeText(mContext, "onOpen : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
#Override
public void onDoubleClick(SwipeLayout layout, boolean surface) {
Toast.makeText(mContext, "DoubleClick : " + position,
Toast.LENGTH_SHORT).show();
}
});
viewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, "onDelete Click : " + position,
Toast.LENGTH_SHORT).show();
}
});
return view;
}
// view holder for managing to recycle of view
public static class ViewHolder {
SwipeLayout swipeLayout;
TextView textView;
View delete;
}
}
ledger_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#FF5534"
android:gravity="center"
android:tag="Bottom3"
android:weightSum="10">
<ImageView
android:id="#+id/trash"
android:layout_width="27dp"
android:layout_height="30dp"
android:layout_weight="1"
android:src="#android:drawable/ic_delete" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="Delete Item?"
android:textColor="#fff"
android:textSize="17sp" />
<Button
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="4"
android:background="#ffffff"
android:text="Yes,Delete"
android:textColor="#FF5534" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#cac6c6"
android:padding="10dp">
<TextView
android:id="#+id/position"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:tag="Hover"
android:text="Do not, for one repulse, forgo the purpose that you resolved to effort. " />
</LinearLayout>
</com.daimajia.swipe.SwipeLayout>
using the way which is marked as an answer will work but there is an another way of doing it too...
adapter class
public class testadapter1 extends RecyclerSwipeAdapter<testadapter1.SimpleViewHolder> {
public static final String TAG = testadapter1.class.getSimpleName();
private static SwipLayoutListener swipLayoutListener;
private static ClickListener clickListener;
String[] time;
Animation animSlide;
boolean ANIM_FLAG = true;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
private int visibleThreshold = 5;
private String phone;
private String email;
public static class SimpleViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
SwipeLayout swipeLayout;
TextView text;
TextView info;
TextView swipeImage;
LinearLayout linearLayout;
ImageView imageView;
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
Log.e("position", String.valueOf(getAdapterPosition()));
}
public SimpleViewHolder(View itemView) {
super(itemView);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
text = (TextView) itemView.findViewById(R.id.input_cname);
txtdate = (TextView) itemView.findViewById(R.id.date);
id = (TextView) itemView.findViewById(R.id.input_cid);
Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
FontManager.markAsIconContainer(itemView.findViewById(R.id.swipe), iconFont);
swipeImage = itemView.findViewById(R.id.swipeIcon);
imageView = new ImageView(mContext);
call = (TextView) itemView.findViewById(R.id.call_btn);
sms = (TextView) itemView.findViewById(R.id.sms_btn);
mail = (TextView) itemView.findViewById(R.id.email_btn);
info = (TextView) itemView.findViewById(R.id.detail_btn);
call.setTypeface(iconFont);
sms.setTypeface(iconFont);
mail.setTypeface(iconFont);
info.setTypeface(iconFont);
swipeLayout.addDrag(SwipeLayout.DragEdge.Left, linearLayout);
itemView.setOnClickListener(this);
swipeLayout.addSwipeListener(new SimpleSwipeListener() {
#Override
public void onOpen(SwipeLayout layout) {
if (swipLayoutListener != null) {
swipLayoutListener.onOpen(layout, getAdapterPosition());
}
}
});
}
}
private static Context mContext;
ArrayList<HashMap<String, String>> mDataset;
public testadapter1(Context mContext, ArrayList<HashMap<String, String>> objects, RecyclerView listView) {
this.mContext = mContext;
this.mDataset = objects;
if (listView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) listView
.getLayoutManager();
listView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView listView,
int dx, int dy) {
super.onScrolled(listView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ledger_layout, parent, false);
return new SimpleViewHolder(view);
}
public interface ClickListener {
void onItemClick(int position, View v);
}
#Override
public void onBindViewHolder(final SimpleViewHolder viewHolder, final int position) {
viewHolder.txtdate.setText(mDataset.get(position).get("date"));
viewHolder.id.setText("Amount: ₹ " + viewHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// HashMap<String, String> mDataset = getItem1(position);
Intent intent = new Intent(mContext, LedgerDetailActivity.class);
intent.putExtra("ledger_name", String.valueOf(mDataset.get(position).get("ledger_name")));
// Log.e("intent", mDataset.get("ledger_name"));
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
if (mDataset == null) {
Log.d(TAG, "getCount: 0");
return 0;
} else {
Log.d(TAG, "getCount: " + mDataset.size());
return mDataset.size();
}
}
#Override
public int getSwipeLayoutResourceId(int position) {
return R.id.swipe;
}
public void addSwipeListener(SwipLayoutListener swipLayoutListener) {
testadapter1.swipLayoutListener = swipLayoutListener;
}
public interface SwipLayoutListener {
void onOpen(SwipeLayout layout, int position);
}
fragment layout
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/frame3"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/list_ledger"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"/>
<!-- Adding bottom sheet after main content -->
</android.support.v4.widget.SwipeRefreshLayout>
adapter layout
<?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
swipe:leftEdgeSwipeOffset="0dp"
swipe:rightEdgeSwipeOffset="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center"
android:weightSum="7">
<RelativeLayout
android:id="#+id/relativeLayoutSms"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/call_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_phone"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/call_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Call"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutCall"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/sms_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_sms"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sms_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="SMS"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutMail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/email_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_mail"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/email_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Email"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayoutInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center">
<com.mikepenz.iconics.view.IconicsTextView
android:id="#+id/detail_btn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="1"
android:text="#string/icon_info"
android:textColor="#color/white"
android:textSize="20sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/detail_btn"
android:layout_centerHorizontal="true"
android:gravity="center"
android:paddingTop="5dp"
android:text="Details"
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:id="#+id/input_cname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/date"
android:layout_marginEnd="5dp"
android:layout_toStartOf="#id/amount"
android:ellipsize="end"
android:maxLines="1"
android:textColor="#color/colorAccent"
android:textSize="16sp" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/input_cname"
android:layout_marginStart="10dp"
android:paddingTop="2dp"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/input_cid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginEnd="2dp"
android:layout_marginStart="10dp"
android:paddingEnd="5dp"
android:textAlignment="viewEnd"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/gp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignStart="#+id/input_cid"
android:layout_below="#+id/input_cname"
android:textAlignment="viewEnd"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="14sp"
android:visibility="gone" />
<TextView
android:id="#+id/swipeIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#id/gp"
android:layout_marginTop="14dp"
android:paddingStart="6dp"
android:visibility="gone" />
</RelativeLayout>
It's been a long time but I had the same issue. It took hours to solve the problem but the solution is here. This WARNING is from the daimajia's wiki.
ATTENTION: Never bind listeners or fill values in generateView. Just generate the view and do everything else in fillValues (e.g using your holder class) See issues #14 and #17
You can find detailed solution here : Solution to your position problem from daimajia's wiki
And sample code is like this :
//ATTENTION: Never bind listener or fill values in generateView.
// You have to do that in fillValues method.
#Override
public View generateView(int position, ViewGroup parent) {
return LayoutInflater.from(mContext).inflate(R.layout.grid_item, null);
}
#Override
public void fillValues(int position, View convertView) {
TextView t = (TextView)convertView.findViewById(R.id.position);
t.setText((position + 1 )+".");
}
You should do everything in fillValues() function. position value here is always right.
Just follow this rule and everything will be fine with your Swipe ListView.
I try to use a GridView object in a specific fragment in my app.
I created a layout file for the grid item and in the layout editor, the preview image looks good, as expected.
The problem arises when I run the app in my emulator. The whole item layout gets shrinked and the image I put in the middle suddenly jumps to the top of the layout.
Screenshot of the layout editor:
https://i.gyazo.com/8ed96ed19719a578388cc48aba6829f8.png
Screenshot of the emulator:
https://i.gyazo.com/cca0a32b3d102025df5d5369dc7c0efc.png
Here is the xml code for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="#+id/documents_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:columnWidth="#dimen/document_grid_item_width"
android:gravity="center"
android:horizontalSpacing="0dp"
android:verticalSpacing="0dp"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform" />
<RelativeLayout
android:id="#+id/empty_view_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/empty_view_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:src="#drawable/recent_empty_view" />
<ImageView
android:id="#+id/empty_view_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/empty_view_image"
android:layout_below="#+id/empty_view_image"
android:layout_marginEnd="7dp"
android:scaleX="0.75"
android:scaleY="0.75"
android:src="#drawable/empty_view_arrow" />
</RelativeLayout>
</RelativeLayout>
Here is the item layout xml code:
<?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"
android:layout_width="#dimen/document_grid_item_width"
android:layout_height="#dimen/document_grid_item_height"
android:gravity="center"
android:orientation="vertical"
android:weightSum="1">
<FrameLayout
android:id="#+id/draft_frame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.9"
android:background="#drawable/document_grid_item_bg"
android:focusable="true"
android:foreground="?android:selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/draft_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/draft_icon" />
<ImageView
android:id="#+id/draft_more_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"
app:srcCompat="#drawable/ic_more" />
</RelativeLayout>
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="0.1">
<TextView
android:id="#+id/draft_date_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="20 May 17"
android:textSize="11sp" />
</RelativeLayout>
</LinearLayout>
Here is the adapter code:
package com.silverfix.dgdeditor.adapters;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.silverfix.dgdeditor.R;
import com.silverfix.dgdeditor.utils.DocumentPack;
import com.silverfix.dgdeditor.utils.views.ViewClickListener;
import com.silverfix.dgdeditor.utils.views.ViewLongClickListener;
import java.util.List;
/**
* Created by David on 14/05/2017.
*/
public class DraftsGridAdapter extends BaseAdapter {
// Listeners
private ViewClickListener clickListener;
private ViewLongClickListener longClickListener;
private Activity context;
private List<DocumentPack> dataSet;
private int clickedItemPos = -1;
public DraftsGridAdapter(Activity context, List<DocumentPack> dataSet) {
this.context = context;
this.dataSet = dataSet;
}
public void setClickedItemPosition(int clickedItemPos) {
this.clickedItemPos = clickedItemPos;
}
public int getClickedItemPosition() {
return clickedItemPos;
}
public void setClickListener(ViewClickListener clickListener) {
this.clickListener = clickListener;
}
public void setLongClickListener(ViewLongClickListener longClickListener) {
this.longClickListener = longClickListener;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public Object getItem(int position) {
return dataSet.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final DocumentPack pack = dataSet.get(position);
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.draft_grid_item, null);
DraftViewHolder viewHolder = new DraftViewHolder(context, convertView);
convertView.setTag(viewHolder);
}
// Instance of a view holder from the tag of the convertView
DraftViewHolder viewHolder = (DraftViewHolder) convertView.getTag();
// Set the adapter position to the current view holder
viewHolder.setAdapterPosition(position);
// Bind the click listeners to the root view of the view holder
// viewHolder.bindClick(clickListener);
// viewHolder.bindLongClick(longClickListener);
// Bind the data to the view holder
viewHolder.bindData(pack);
return convertView;
}
private class DraftViewHolder implements View.OnCreateContextMenuListener {
private View.OnClickListener clickListener;
private View.OnLongClickListener onLongClickListener;
private View rootView;
private ImageView moreButton;
private TextView date;
private int position;
public DraftViewHolder(final Activity context, final View rootView) {
this.rootView = rootView;
date = (TextView) rootView.findViewById(R.id.draft_date_tv);
moreButton = (ImageView) rootView.findViewById(R.id.draft_more_button);
context.registerForContextMenu(rootView);
rootView.setOnCreateContextMenuListener(this);
moreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.openContextMenu(rootView);
setClickedItemPosition(position);
}
});
}
void setAdapterPosition(int position) {
this.position = position;
}
void bindClick(final ViewClickListener clickListener) {
this.clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
clickListener.onClick(position);
}
};
rootView.setOnClickListener(this.clickListener);
}
void bindLongClick(final ViewLongClickListener longClickListener) {
this.onLongClickListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
longClickListener.onLongClick(position);
return false;
}
};
rootView.setOnLongClickListener(this.onLongClickListener);
}
void bindData(DocumentPack draft) {
String formatDate = draft.getFormattedDate();
date.setText(formatDate);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
}
This worked for me, You can try...
`<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp" >
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="10dp" />
`
If this don't work you can also try to use android:stretchMode="columnWidth"
I am using two ListViews (List1 has data and List2 is empty).
The user can enter a name as input and if List1 contains name and the add Button is pressed then marks should be decreased by 1 and both the ListViews should be updated.
Example:
If List1 has 10 marks and a name is entered then List1 should have marks set to 9 and List2 should have marks set to 1.
If the list1 has same names then index with first position name should be updated. Now both the values are updated with same name.
If we did this 10 times then List1 names should be removed and List2 has marks set to 10.
Example 2:
Suppose List1 has marks set to 8 and List2 marks set to 2. If the sub button is pressed then both should lists should be added. At this point, List2 should be deleted and List1 should have total marks as 10.
Below is the logic I have used however it is not working it is updating multiple rows with same names.
HomeAct class
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class HomeAct extends Activity {
List<DocItem> docDet1 = new ArrayList<DocItem>();
List<DocItem> docDet2 = new ArrayList<DocItem>();
ListView lv1, lv2;
EditText editText;
Button btn1, btn2;
DocDetAdapter adapter1, adapter2;
int n=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_act);
lv1 = (ListView)findViewById(R.id.lv_det1);
lv2 = (ListView)findViewById(R.id.lv_det2);
editText = (EditText)findViewById(R.id.editText1);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
adapter1 = new DocDetAdapter(1);
adapter2 = new DocDetAdapter(2);
docDet1.add(new DocItem("1", "john", 20));
docDet1.add(new DocItem("2", "john", 20));
docDet1.add(new DocItem("3", "shaun", 60));
docDet1.add(new DocItem("4", "joy", 10));
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DocItem changeItem = null;
for (int i = 0; i < docDet1.size(); i++) {
DocItem docItem = docDet1.get(i);
if (docItem.name.equals(editText.getText().toString())) {
changeItem = docDet1.get(i);
changeItem.marks = changeItem.marks - 1;
if (findDocItem(editText.getText().toString()) != null) {
DocItem docI = findDocItem(editText.getText()
.toString());
docI.marks = docI.marks + 1;
} else {
docDet2.add(new DocItem(changeItem.docNo,
changeItem.name, 1));
}
}
if (docItem.marks == 0) {
docDet1.remove(i);
}
}
adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged();
editText.setText("");
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int changedmarks=0;
DocItem item = null;
for (int i = 0; i < docDet2.size(); i++) {
DocItem docItem = docDet2.get(i);
item = docDet2.get(i);
if (docItem.name.equals(editText.getText().toString())) {
changedmarks =docDet2.get(i).marks;
docDet2.remove(i);
}
}
if(findDocItem2(editText.getText().toString())!=null )
{
DocItem docitem = findDocItem2(editText.getText().toString());
docitem.marks = docitem.marks+ changedmarks;
}
else{
System.out
.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- else loop ");
docDet1.add(0,item);
}
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
editText.setText("");
}
});
}
private class DocDetAdapter extends BaseAdapter {
int mode; // 1 or 2
public DocDetAdapter(int mode) {
this.mode = mode;
}
#Override
public int getCount() {
if (mode == 1)
return docDet1.size();
else
return docDet2.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.row_tray_det, null);
TextView tvItemName = (TextView) convertView
.findViewById(R.id.tv_item_name);
TextView tvRack = (TextView) convertView.findViewById(R.id.tv_rack);
TextView tvQty = (TextView) convertView.findViewById(R.id.tv_qty);
DocItem invItem;
if (mode == 1)
invItem = docDet1.get(position);
else
invItem = docDet2.get(position);
tvItemName.setText(invItem.docNo);
tvRack.setText(invItem.name);
tvQty.setText(invItem.marks + "");
return convertView;
}
}
}
DocItem class
public class DocItem {
public String docNo, name;
public Integer marks;
public DocItem(String docNo, String name, Integer marks) {
super();
this.docNo = docNo;
this.name = name;
this.marks = marks;
}
}
home_act.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="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="3"
android:text="Add" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="3"
android:text="Sub" />
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 1"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<ListView
android:id="#+id/lv_det1"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 2"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<ListView
android:id="#+id/lv_det2"
android:layout_width="fill_parent"
android:layout_height="250dp" />
</LinearLayout>
row_tray_det
<?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" >
<View
android:id="#+id/v_doc_seperator"
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#color/blue"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/row_bg_transparent_white"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_rack"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:gravity="center_vertical"
android:padding="10dp"
android:text="Sl no"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="Name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:paddingRight="3dp"
android:text="Marks"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
I could really use help, thanks in advance.
i have two adapters and a fragment, and i want to display feeds on two views, one bottom and one recycler view. Although the Json was working with a list adapter. its not working with the recycler view.
here is the main fragment
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardExpand;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.view.CardViewNative;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;
public class FeedFragmentAlternative extends Fragment{
private static final String TAG = FeedFragmentAlternative.class.getSimpleName();
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
private WaveSwipeRefreshLayout mWaveSwipeRefresh;
int duration = 200;
private List<FeedItem> FeedItems;
public static FeedFragmentAlternative newInstance(){
FeedFragmentAlternative feedFragmentAlternative = new FeedFragmentAlternative();
return feedFragmentAlternative;
}
private void refresh(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mWaveSwipeRefresh.setRefreshing(false);
}
},3000);
}
private ExpandablePager pager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.feed_activity_alternate, container, false);
final List<FeedItem> myFeedList = new ArrayList<>();
final FeedExpandableAdapter adapter = new FeedExpandableAdapter(myFeedList);
pager = (ExpandablePager) getActivity().findViewById(R.id.bottom_feed_container);
pager.setAdapter(adapter);
pager.setOnSliderStateChangeListener(new OnSliderStateChangeListener() {
#Override
public void onStateChanged(View page, int index, int state) {
toggleContent(page, state, duration);
}
#Override
public void onPageChanged(View page, int index, int state) {
toggleContent(page, state, 0);
}
});
final RecyclerView mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.feeds_list_recycler_view);
mRecyclerView.setHasFixedSize(true);
final FeedGridAdapter a = new FeedGridAdapter(myFeedList);
a.setListener(new OnItemClickedListener() {
#Override
public void onItemClicked(int index) {
pager.setCurrentItem(index, false);
pager.animateToState(ExpandablePager.STATE_EXPANDED);
}
});
mWaveSwipeRefresh = (WaveSwipeRefreshLayout)view.findViewById(R.id.feed_wave_swipe_layout_refresh_alternate);
mWaveSwipeRefresh.setColorSchemeColors(Color.WHITE, Color.GREEN);
mWaveSwipeRefresh.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
pager.setAdapter(adapter);
mRecyclerView.setAdapter(a);
FeedFragmentAlternative.newInstance();
refresh();
}
});
mWaveSwipeRefresh.setWaveColor(Color.parseColor("#80C5EFF7"));
mWaveSwipeRefresh.setMaxDropHeight((int)(mWaveSwipeRefresh.getHeight() * 0.9));
mRecyclerView.setAdapter(a);
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED);
if (entry != null){
try {
String data = new String (entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e){
e.printStackTrace();
}
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
} else {
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response:" + response.toString());
if (response != null){
parseJsonFeed(response);
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "ERROR:" + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonReq);
}
return view;
}
private void toggleContent(final View page, final int state, int duration){
final int headerHeight = (int) getResources().getDimension(R.dimen.header_height);
if (page != null){
ValueAnimator animator = state == ExpandablePager.STATE_EXPANDED ? ValueAnimator.ofFloat(1,0): ValueAnimator.ofFloat(0,1);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
page.findViewById(R.id.profile_name_header).setTranslationY(25 * (1 - ((Float) animation.getAnimatedValue())));
page.findViewById(R.id.profile_name_header).setTranslationX(-headerHeight * (1 - ((Float)animation.getAnimatedValue())));
page.findViewById(R.id.feed_time_stamp_header).setAlpha(((Float)animation.getAnimatedValue()));
page.findViewById(R.id.profile_pic_header_image).setAlpha(((Float)animation.getAnimatedValue()));
page.findViewById(R.id.feed_like_bottom_sheet).setAlpha(((Float) animation.getAnimatedValue()));
}
});
animator.setDuration((long)(duration * 5));
animator.setInterpolator(new FastOutSlowInInterpolator());
animator.start();
}
}
private void parseJsonFeed(JSONObject response){
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0;i < feedArray.length(); i++){
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
String image = feedObj.isNull("image")? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
String feedUrl = feedObj.isNull("url")? null : feedObj
.getString("url");
item.setUrl(feedUrl);
FeedItems.add(item);
}
} catch (JSONException e){
e.printStackTrace();
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initCards();
}
private void initCards(){
init_standard_header_with_expandcollapse_button();
}
private void init_standard_header_with_expandcollapse_button(){
Card card = new Card(getActivity());
CardHeader header = new CardHeader(getActivity());
header.setButtonExpandVisible(true);
card.addCardHeader(header);
CardExpand expand = new CardExpand(getActivity());
expand.setTitle("expanded");
CardViewNative cardViewNative = (CardViewNative) getActivity().findViewById(R.id.feed_card_style);
cardViewNative.setCard(card);
}
}
the grid adapter is as follows
public class FeedGridAdapter extends RecyclerView.Adapter<FeedGridAdapter.ViewHolder> {
private OnItemClickedListener listener;
private List<FeedItem> mFeedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public static class ViewHolder extends RecyclerView.ViewHolder{
public LoginTextView ProfileNameCell;
public LoginTextView FeedTimesStampCell;
public NetworkImageView ProfilepicCell;
public LoginTextView FeedStatusMgsCell;
public FeedImageView FeedImageViewCell;
public ViewGroup container;
public ViewHolder(RelativeLayout v){
super(v);
container = v;
ProfileNameCell = (LoginTextView) v.findViewById(R.id.client_name_alternate_cell);
FeedTimesStampCell = (LoginTextView) v.findViewById(R.id.time_stamp_alternate_cell);
ProfilepicCell = (NetworkImageView) v.findViewById(R.id.profile_pic_alternate_cell);
FeedStatusMgsCell = (LoginTextView) v.findViewById(R.id.txtStatusMgs_alternate);
FeedImageViewCell = (FeedImageView) v.findViewById(R.id.feedImage1_alternate);
}
}
public FeedGridAdapter(List<FeedItem> feedItems){mFeedItems = feedItems;}
#Override
public FeedGridAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RelativeLayout v = (RelativeLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.feed_card_alternate, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.ProfileNameCell.setText(mFeedItems.get(position).getName());
CharSequence timeStampCell = DateUtils.getRelativeTimeSpanString(
Long.parseLong(mFeedItems.get(position).getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
holder.FeedTimesStampCell.setText(timeStampCell);
if (!TextUtils.isEmpty(mFeedItems.get(position).getStatus())){
holder.FeedStatusMgsCell.setText(mFeedItems.get(position).getStatus());
holder.FeedStatusMgsCell.setVisibility(View.VISIBLE);
} else {
holder.FeedStatusMgsCell.setVisibility(View.GONE);
}
holder.ProfilepicCell.setImageUrl(mFeedItems.get(position).getImge(), imageLoader);
if (mFeedItems.get(position).getImge() != null){
holder.FeedImageViewCell.setImageUrl(mFeedItems.get(position).getImge(), imageLoader);
holder.FeedImageViewCell.setVisibility(View.VISIBLE);
holder.FeedImageViewCell
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
holder.FeedImageViewCell.setVisibility(View.GONE);
}
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClicked(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return mFeedItems.size();
}
public void setListener(OnItemClickedListener listener){this.listener = listener;}
}
and the expandable fragment is
public class FeedExpandableAdapter extends ExpandablePagerAdapter<FeedItem> {
public FeedExpandableAdapter(List<FeedItem> items){super(items);}
private LayoutInflater inflater;
private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
#Override
public Object instantiateItem(ViewGroup container, int position) {
final ViewGroup rootView = (ViewGroup) LayoutInflater.from(container.getContext()).inflate(R.layout.feed_page_alternative, container, false);
if (inflater == null)
inflater = (LayoutInflater)activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
LoginTextView name = (LoginTextView) rootView.findViewById(R.id.profile_name_header);
LoginTextView timestamp = (LoginTextView) rootView.findViewById(R.id.feed_time_stamp_header);
NetworkImageView profilepic = (NetworkImageView) rootView.findViewById(R.id.profile_pic_header_image);
FeedImageView feedImageView = (FeedImageView) rootView.findViewById(R.id.feed_main_image_bottom_sheet);
LoginTextView statusMgs = (LoginTextView) rootView.findViewById(R.id.body_bottom_panel_feed);
name.setText(items.get(position).getName());
CharSequence timeofStamp = DateUtils.getRelativeTimeSpanString(
Long.parseLong(items.get(position).getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeofStamp);
if (!TextUtils.isEmpty(items.get(position).getStatus())){
statusMgs.setText(items.get(position).getStatus());
statusMgs.setVisibility(View.VISIBLE);
} else {
statusMgs.setVisibility(View.GONE);
}
profilepic.setImageUrl(items.get(position).getProfilePic(), imageLoader);
if (items.get(position).getImge() != null) {
feedImageView.setImageUrl(items.get(position).getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return attach(container, rootView, position);
}
}
the error shown is like this -
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.telenav.expandablepager.ExpandablePager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference
at com.evolustudios.askin.askin.src.fragments.FeedFragmentAlternative.onCreateView(FeedFragmentAlternative.java:86)
can anyone tell me why its returning null?
its possible duplicate, but i cannot figure out why its returning null
xml - feed_card_alternate
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="350dp"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<it.gmariotti.cardslib.library.view.CardViewNative
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feed_card_style"
style="#style/card_external">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frame_list_card_item_alternate"
android:background="#drawable/cardpanel"
android:paddingTop="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:id="#+id/feed_top_panel_alternate"
android:paddingBottom="25dp">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/profile_pic_alternate_cell"
android:scaleType="fitCenter"
android:paddingTop="15dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingTop="15dp">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/client_name_alternate_cell"
android:textSize="15dp"
android:textStyle="bold"/>
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time_stamp_alternate_cell"
android:textColor="#color/timestamp"
android:textSize="13dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/feed_other_content_alternate"
android:layout_below="#+id/feed_top_panel_alternate">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtStatusMgs_alternate"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="13dp" />
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtUrl_alternate"
android:linksClickable="true"
android:paddingBottom="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="#color/link" />
<com.evolustudios.askin.askin.src.Utils.FeedImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/feedImage1_alternate"
android:background="#80FFFFFF"
android:scaleType="fitXY"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
</FrameLayout>
</it.gmariotti.cardslib.library.view.CardViewNative>
feed_activity_alternate.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feed_wave_swipe_layout_refresh_alternate">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feeds_list_recycler_view"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:scrollbars="vertical"
tools:listitem="#layout/feed_item_list_new">
</android.support.v7.widget.RecyclerView>
<com.telenav.expandablepager.ExpandablePager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom_feed_container"
android:layout_gravity="bottom"
app:animation_duration="200"
app:collapsed_height="#dimen/header_height"/>
</jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout>
feed_page_alternative
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/pumice">
<include
layout="#layout/feed_header_layout"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="250sp"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:paddingTop="10dp"
android:id="#+id/feed_bottom_panel_first_container">
<com.evolustudios.askin.askin.src.Utils.FeedImageView
android:layout_width="270sp"
android:layout_height="match_parent"
android:background="#color/edward"
android:id="#+id/feed_main_image_bottom_sheet"
android:scaleType="fitCenter"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:scrollbars="none">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/feed_extra_iamge_list_view_bootom_panel">
</ListView>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="#+id/feed_bottom_panel_second_container"
android:baselineAligned="false"
android:orientation="horizontal"
android:weightSum="5">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_very_satisfied_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:src="#drawable/ic_sentiment_satisfied_black_24dp"
android:scaleType="fitCenter"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_neutral_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_dissatisfied_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/ic_sentiment_very_dissatisfied_black_24dp"
android:scaleType="fitCenter"
android:padding="5dp"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/feed_bottom_panel_third_container"
android:baselineAligned="false"
android:orientation="horizontal"
android:weightSum="5">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/very_liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/neutral_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/not_liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/very_not_liked_number_bottom_panel"
android:text="100"
android:gravity="center"
android:textColor="#color/ming"/>
</RelativeLayout>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:paddingLeft="22dp"
android:paddingRight="22dp"
android:paddingTop="15dp"
android:paddingBottom="15dp">
<com.evolustudios.askin.askin.src.customfonts.LoginTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/body_bottom_panel_feed"
android:text="Body"
android:textSize="20dp"/>
</ScrollView>
Change,
pager = (ExpandablePager) getActivity().findViewById(R.id.bottom_feed_container);
to
pager = (ExpandablePager) view.findViewById(R.id.bottom_feed_container);
Also change,
final RecyclerView mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.feeds_list_recycler_view);
to
final RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.feeds_list_recycler_view);