- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我正在获取 JSONArray 中的数据:
{ "chatArray": [
{
"msg_id": "193",
"user_id": "15235",
"first_name": "Vishal",
"user_name": "vishal13",
"message": "twilio",
"chat_time": "2017-06-30 11:28:00"
},
{
"msg_id": "192",
"user_id": "15321",
"first_name": "Rohit",
"user_name": "rohit12",
"message": "how are you?",
"chat_time": "2017-06-30 11:28:00"
}]}
我在 RecyclerView
中显示完整数据,现在我的要求是我想像 whatsapp 一样在他们上面显示他们日子的标题。
public ChatScreenAdapter(Activity con, List<EquityDetails> list, String senderImage, String receiverImage) {
this.items = list;
this.context = con;
this.senderImage = senderImage;
this.receiverImage = receiverImage;
this.arraylist = new ArrayList<EquityDetails>();
this.arraylist.addAll(items);
if (con != null) {
typeface_normal = Typeface.createFromAsset(con.getAssets(), "fonts/arial_regular.ttf");
share = context.getSharedPreferences("quiz_sharePrefs", 0);
login_checked = share.getBoolean("ConfirmLogin", false);
if (login_checked) {
user_id = share.getInt("user_id", 0);
}
}
}
public static int getTimeRemaining(long timeStamp) {
Calendar sDate = toCalendar(timeStamp);
Calendar eDate = toCalendar(System.currentTimeMillis());
// Get the represented date in milliseconds
long milis1 = sDate.getTimeInMillis();
long milis2 = eDate.getTimeInMillis();
// Calculate difference in milliseconds
long diff = Math.abs(milis2 - milis1);
return (int) (diff / (24 * 60 * 60 * 1000));
}
private static Calendar toCalendar(long timestamp) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.advisory_left_side_chat_screen, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final EquityDetails itemList = items.get(position);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
Glide.with(context).load(Constants.Profile_images + "" + senderImage).asBitmap().centerCrop().placeholder(R.drawable.default_usr).into(new BitmapImageViewTarget(holder.userImageViewRight) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.userImageViewRight.setImageDrawable(circularBitmapDrawable);
}
});
Glide.with(context).load(receiverImage + "").asBitmap().centerCrop().placeholder(R.drawable.default_usr).into(new BitmapImageViewTarget(holder.userImageViewLeft) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.userImageViewLeft.setImageDrawable(circularBitmapDrawable);
}
});
if (Integer.parseInt(itemList.getId()) == user_id) {
holder.leftSideLayout.setVisibility(View.GONE);
holder.rightSideLayout.setVisibility(View.VISIBLE);
holder.messageTextViewRight.setText(itemList.getReviews_message() + "");
holder.nameTextViewRight.setText(itemList.getName());
holder.timeTvRight.setText(parseDateToddMMyyyy(itemList.getCreated_time()));
} else {
holder.leftSideLayout.setVisibility(View.VISIBLE);
holder.rightSideLayout.setVisibility(View.GONE);
holder.messageTextViewLeft.setText(itemList.getReviews_message() + "");
holder.nameTextViewLeft.setText(itemList.getName());
holder.timeTvLeft.setText(parseDateToddMMyyyy(itemList.getCreated_time()));
}
long previousTs = 0;
if (position > 1) {
if (getTimeRemaining(parseDay(itemList.getCreated_time())) == 0)
holder.dayTextView.setText("Today");
else if (getTimeRemaining(parseDay(itemList.getCreated_time())) == 1)
holder.dayTextView.setText("Yesterday");
else
holder.dayTextView.setText("convert the date and show");
}
}
public long parseDay(String time) {
// Make a Calendar whose DATE part is some time yesterday.
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DATE, -1);
String inputPattern = "yyyy-MM-dd HH:mm:ss";
String outputPattern = "dd MM";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
Date date = null;
String str = null;
Date d = null;
try {
date = inputFormat.parse(time);
if (date.before(cal.getTime())) {
// myDate must be yesterday or earlier
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
str = outputFormat.format(date);
d = outputFormat.parse(str);
} else {
// myDate must be today or later
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
str = outputFormat.format(date);
d = outputFormat.parse(str);
}
} catch (ParseException e) {
e.printStackTrace();
}
return d.getTime();
}
public String parseDateToddMMyyyy(String time) {
// Make a Calendar whose DATE part is some time yesterday.
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.DATE, -1);
String inputPattern = "yyyy-MM-dd HH:mm:ss";
String outputPattern = "dd MMM";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(time);
/* if (date.before(cal.getTime())) {
// myDate must be yesterday or earlier
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
str = outputFormat.format(date);
} else {*/
// myDate must be today or later
outputPattern = "hh:mm aa";
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
str = outputFormat.format(date);
//}
} catch (ParseException e) {
e.printStackTrace();
}
return str.toUpperCase();
}
@Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout leftSideLayout;
private RelativeLayout topLayoutLeft;
private ImageView userImageViewLeft;
private TextView nameTextViewLeft;
private TextView staticTextViewLeft;
private TextView messageTextViewLeft;
private TextView timeTvLeft;
private RelativeLayout rightSideLayout;
private RelativeLayout topLayoutRight;
private ImageView userImageViewRight;
private TextView nameTextViewRight;
private TextView staticTextViewRight;
private TextView messageTextViewRight;
private TextView timeTvRight;
private TextView dayTextView;
public MyViewHolder(View view) {
super(view);
leftSideLayout = (RelativeLayout) view.findViewById(R.id.left_side_layout);
topLayoutLeft = (RelativeLayout) view.findViewById(R.id.top_layout_left);
userImageViewLeft = (ImageView) view.findViewById(R.id.user_image_view_left);
nameTextViewLeft = (TextView) view.findViewById(R.id.name_textView_left);
staticTextViewLeft = (TextView) view.findViewById(R.id.static_textView_left);
messageTextViewLeft = (TextView) view.findViewById(R.id.message_textView_left);
timeTvLeft = (TextView) view.findViewById(R.id.time_tv_left);
rightSideLayout = (RelativeLayout) view.findViewById(R.id.right_side_layout);
topLayoutRight = (RelativeLayout) view.findViewById(R.id.top_layout_right);
userImageViewRight = (ImageView) view.findViewById(R.id.user_image_view_right);
nameTextViewRight = (TextView) view.findViewById(R.id.name_textView_right);
staticTextViewRight = (TextView) view.findViewById(R.id.static_textView_right);
messageTextViewRight = (TextView) view.findViewById(R.id.message_textView_right);
timeTvRight = (TextView) view.findViewById(R.id.time_tv_right);
dayTextView = (TextView) view.findViewById(R.id.day_textView);
nameTextViewLeft.setTypeface(typeface_normal);
nameTextViewRight.setTypeface(typeface_normal);
messageTextViewLeft.setTypeface(typeface_normal);
messageTextViewRight.setTypeface(typeface_normal);
timeTvLeft.setTypeface(typeface_normal);
timeTvRight.setTypeface(typeface_normal);
dayTextView.setTypeface(typeface_normal);
dayTextView.setVisibility(View.GONE);
}
}
但是这里 dayTextView
不是根据日期显示每个项目的上方。我只想在相应消息的顶部显示每个日期一次。
最佳答案
主要 Activity
public class MainActivity extends AppCompatActivity {
private ChatAdapter chatAdapter;
private RecyclerView recyclerView;
private Context context;
private int loggedInUserID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindRecyclerView();
// TODO get logged in user id and initialize into 'loggedInUserID'
}
@Override
protected void onResume() {
super.onResume();
getData();
}
private void getData() {
/**
*Your server call to get data and parse json to your appropriate model
* after parsing json to model simply call the
*/
List<ChatModel> chatModelList = ParseData.chatParser(jsonArray);
groupDataIntoHashMap(chatModelList);
}
private void bindRecyclerView() {
chatAdapter = new ChatAdapter(null);
chatAdapter.setUser(loggedInUserID);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(chatAdapter);
}
private void groupDataIntoHashMap(List<ChatModel> chatModelList) {
LinkedHashMap<String, Set<ChatModel>> groupedHashMap = new LinkedHashMap<>();
Set<ChatModel> list = null;
for (ChatModel chatModel : chatModelList) {
//Log.d(TAG, travelActivityDTO.toString());
String hashMapKey = DateParser.convertDateToString(chatModel.getChatTime());
//Log.d(TAG, "start date: " + DateParser.convertDateToString(travelActivityDTO.getStartDate()));
if (groupedHashMap.containsKey(hashMapKey)) {
// The key is already in the HashMap; add the pojo object
// against the existing key.
groupedHashMap.get(hashMapKey).add(chatModel);
} else {
// The key is not there in the HashMap; create a new key-value pair
list = new LinkedHashSet<>();
list.add(chatModel);
groupedHashMap.put(hashMapKey, list);
}
}
//Generate list from map
generateListFromMap(groupedHashMap);
}
private List<ListObject> generateListFromMap(LinkedHashMap<String, Set<ChatModel>> groupedHashMap) {
// We linearly add every item into the consolidatedList.
List<ListObject> consolidatedList = new ArrayList<>();
for (String date : groupedHashMap.keySet()) {
DateObject dateItem = new DateObject();
dateItem.setDate(date);
consolidatedList.add(dateItem);
for (ChatModel chatModel : groupedHashMap.get(date)) {
ChatModelObject generalItem = new ChatModelObject();
generalItem.setChatModel(chatModel);
consolidatedList.add(generalItem);
}
}
chatAdapter.setDataChange(consolidatedList);
return consolidatedList;
}
}
聊天模型.java
public class ChatModel implements Serializable {
private String messageId;
private int userId;
private String firstName;
private String userName;
private String message;
private Date chatTime;
//TODO generate getter and setter
}
ListObject.java(确定消息的类型)
public abstract class ListObject {
public static final int TYPE_DATE = 0;
public static final int TYPE_GENERAL_RIGHT = 1;
public static final int TYPE_GENERAL_LEFT = 2;
abstract public int getType(int userId);
}
日期对象.java
public class DateObject extends ListObject {
private String date;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@Override
public int getType(int userId) {
return TYPE_DATE;
}
}
聊天模型对象.java
public class ChatModelObject extends ListObject {
private ChatModel chatModel;
public ChatModel getChatModel() {
return chatModel;
}
public void setChatModel(ChatModel chatModel) {
this.chatModel = chatModel;
}
@Override
public int getType(int userId) {
if (this.chatModel.getUserId() == userId) {
return TYPE_GENERAL_RIGHT;
} else
return TYPE_GENERAL_LEFT;
}
}
DateParse.java 解析日期以对聊天进行分组
public class DateParser {
private static DateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
public static String convertDateToString(Date date) {
String strDate = "";
strDate = dateFormat1.format(date);
return strDate;
}
}
聊天适配器.java
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ListObject> listObjects;
private int loggedInUserId;
public ChatAdapter(List<ListObject> listObjects) {
this.listObjects = listObjects;
}
public void setUser(int userId) {
this.loggedInUserId = userId;
}
public void setDataChange(List<ListObject> asList) {
this.listObjects = asList;
//now, tell the adapter about the update
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ListObject.TYPE_GENERAL_RIGHT:
View currentUserView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_chat_list_row_right, parent, false);
viewHolder = new ChatRightViewHolder(currentUserView); // view holder for normal items
break;
case ListObject.TYPE_GENERAL_LEFT:
View otherUserView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_chat_list_row_left, parent, false);
viewHolder = new ChatLeftViewHolder(otherUserView); // view holder for normal items
break;
case ListObject.TYPE_DATE:
View v2 = inflater.inflate(R.layout.date_row, parent, false);
viewHolder = new DateViewHolder(v2);
break;
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()) {
case ListObject.TYPE_GENERAL_RIGHT:
ChatModelObject generalItem = (ChatModelObject) listObjects.get(position);
ChatRightViewHolder chatViewHolder = (ChatRightViewHolder) viewHolder;
chatViewHolder.bind(generalItem.getChatModel());
break;
case ListObject.TYPE_GENERAL_LEFT:
ChatModelObject generalItemLeft = (ChatModelObject) listObjects.get(position);
ChatLeftViewHolder chatLeftViewHolder = (ChatLeftViewHolder) viewHolder;
chatLeftViewHolder.bind(generalItemLeft.getChatModel());
break;
case ListObject.TYPE_DATE:
DateObject dateItem = (DateObject) listObjects.get(position);
DateViewHolder dateViewHolder = (DateViewHolder) viewHolder;
dateViewHolder.bind(dateItem.getDate());
break;
}
}
@Override
public int getItemCount() {
if (listObjects != null) {
return listObjects.size();
}
return 0;
}
@Override
public int getItemViewType(int position) {
return listObjects.get(position).getType(loggedInUserId);
}
public ListObject getItem(int position) {
return listObjects.get(position);
}
}
当前用户消息的ChatRightViewHolder.java
public class ChatRightViewHolder extends RecyclerView.ViewHolder {
private final String TAG = ChatRightViewHolder.class.getSimpleName();
public ChatRightViewHolder(View itemView) {
super(itemView);
//TODO initialize your xml views
}
public void bind(final ChatModel chatModel) {
//TODO set data to xml view via textivew.setText();
}
}
ChatLeftViewHolder.java 用于显示其他用户消息。
public class ChatLeftViewHolder extends RecyclerView.ViewHolder {
private final String TAG = ChatRightViewHolder.class.getSimpleName();
public ChatLeftViewHolder(View itemView) {
super(itemView);
//TODO initialize your xml views
}
public void bind(final ChatModel chatModel) {
//TODO set data to xml view via textivew.setText();
}
}
DateViewHolder.java 显示日期
public class DateViewHolder extends RecyclerView.ViewHolder {
public DateViewHolder(View itemView) {
super(itemView);
//TODO initialize your xml views
}
public void bind(final String date) {
//TODO set data to xml view via textivew.setText();
}
}
关于android - 如何在 Android RecyclerView 中显示一组项目上方的日期/日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44840913/
我在另一个 RecyclerView(parentRecyclerView) 中实现了 RecyclerView(childRecyclerView),图片说明了所有的实现: 我想编写一个 espre
我正在构建一个应用程序,它使用ViewPager2在页面之间水平滚动,每个页面都有一个垂直滚动的内容RecyclerView,其中每个列表的第一个位置都有一行水平滚动小部件,例如附加到寻呼机指示器类型
我正在尝试实现一个水平的 recyclerview 并且 recyclerview 的每个项目都将是一个具有网格布局的垂直 recyclerview。我面临的问题是,当我尝试垂直滚动子 recycle
我使用显示条目列表的 RecyclerView。每个条目都托管另一个 RecyclerView,它是一个图像列表。 我现在想让这个嵌套的 RecyclerView 可点击,而不是它的项目,而是整个 V
我正在尝试将手机中的图像加载到我的回收 View 中。 到目前为止,我已经创建了一个 recyclerview.adapter 和一个 gridlayoutmanager,并将它们附加到我的 recy
我需要一个可扩展 View ,其中父/可扩展标题将具有文本和下拉箭头。每个此类标题的子项应该是在网格结构中具有多个项目的 View 。 (有点像带有 GridLayoutManager 的回收器 Vi
我正在使用显示不同类别列表的 RecyclerView。每行项目还包含 RecyclerView 以显示类别项目列表。父级 RecyclerView 由垂直 LinearLayoutManager 填
我正在更新一个旧的 Android 项目,现在我从 RecyclerView 中反复收到这条日志语句: W/RecyclerView:RecyclerView 不支持滚动到绝对位置。改为使用 scro
在我的 Adapter 中,我调用 LayoutManager.ChildAt(position) 来获取 itemview,但是我得到的 View 不是匹配的 itemview,当我调用 notif
我正在从 ListView 迁移到 RecyclerView,但是在 SQLite 中输入一些数据后,我的列表没有使用 notifyDataSetChanged() 更新;所以我总是要调用setAda
我正在用 Google Now Cards 的风格创建一组 5 张卡片。我首先关注的是总体布局。 我正在使用 CardView 和 RecyclerView ,我想要实现的是这样的: 这是我的 Car
在我的应用程序中,我有一个 RecyclerView,其中包含一个简单的项目 View ,每行包含一个 TextView 和一个 Spinner。 用户从操作栏中单击“保存”后,我需要遍历所有项目并获
我正在尝试检查 RecyclerView 中是否可以看到某些特定项目;但我无法实现。请帮助我确定我的项目是否在 RecyclerView 中完全可见。 mrecylerView.addOnScroll
我有一个提要片段,它的主要元素是帖子的 RecyclerView。 我正在使用 Lisa Wray 的 Groupie 库管理回收站 https://github.com/lisawray/group
我有这两个类似的行为回收器 View 适配器,它们之间的唯一区别是 onclick 方法和传递给它们的对象。所以,我正在考虑将类 B 设计为从回收器 View 适配器继承,这样我就可以更改构造函数来执
这很奇怪。我对这个问题感到沮丧。我将数据保存在 ArrayList 中。当我将数据放在 RecyclerView 上时。数据未显示在列表中。这是我的代码 listOrder.forEach { ord
编辑我通过使用 CoordinatorLayout 和 AppBarLayout 作为 header 和 TabLayout 的包装解决了这个问题。本来应该很明显,但是哦,好吧。 原始问题:我有一个设
我有一个回收 View 。我想从其适配器类更新回收器 View 。我尝试了 notiftDataSetChanged( ) 但它只适用于主类。下面是 recyclerview 适配器类的代码。 pac
我正在使用具有不同 viewholders 的 recyclerview(具有垂直 LinearLayout),其中一个有另一个 RecyclerView(带有水平 LL)。在第二个 recycler
我想创建一个与 Google Play Store 或 Netflix App 类似的布局,其中在单个 RecyclerView 中基本上有多个水平 RecyclerView。如果这不是他们做事的方式
我是一名优秀的程序员,十分优秀!