Browse Source

generify posts list to topic items

pull/55/head
Thodoris1999 6 years ago
parent
commit
7db9c43fd8
  1. 38
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java
  2. 779
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java
  3. 5
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicParser.java
  4. 5
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTask.java
  5. 7
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTaskResult.java
  6. 4
      app/src/main/java/gr/thmmy/mthmmy/model/Poll.java
  7. 3
      app/src/main/java/gr/thmmy/mthmmy/model/TopicItem.java
  8. 13
      app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java

38
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java

@ -12,7 +12,6 @@ import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar; import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat; import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDelegate; import android.support.v7.app.AppCompatDelegate;
@ -50,6 +49,7 @@ import gr.thmmy.mthmmy.editorview.EmojiKeyboard;
import gr.thmmy.mthmmy.model.Bookmark; import gr.thmmy.mthmmy.model.Bookmark;
import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyPage; import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.model.TopicItem;
import gr.thmmy.mthmmy.utils.CustomLinearLayoutManager; import gr.thmmy.mthmmy.utils.CustomLinearLayoutManager;
import gr.thmmy.mthmmy.utils.HTMLUtils; import gr.thmmy.mthmmy.utils.HTMLUtils;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers; import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
@ -85,7 +85,7 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
/** /**
* Holds a list of this topic's posts * Holds a list of this topic's posts
*/ */
private ArrayList<Post> postsList; private ArrayList<TopicItem> topicItems;
//Reply related //Reply related
private FloatingActionButton replyFAB; private FloatingActionButton replyFAB;
//Topic's pages related //Topic's pages related
@ -170,7 +170,7 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
progressBar = findViewById(R.id.progressBar); progressBar = findViewById(R.id.progressBar);
emojiKeyboard = findViewById(R.id.emoji_keyboard); emojiKeyboard = findViewById(R.id.emoji_keyboard);
postsList = new ArrayList<>(); topicItems = new ArrayList<>();
recyclerView = findViewById(R.id.topic_recycler_view); recyclerView = findViewById(R.id.topic_recycler_view);
recyclerView.setHasFixedSize(true); recyclerView.setHasFixedSize(true);
@ -179,7 +179,7 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
getApplicationContext(), topicPageUrl); getApplicationContext(), topicPageUrl);
recyclerView.setLayoutManager(layoutManager); recyclerView.setLayoutManager(layoutManager);
topicAdapter = new TopicAdapter(this, postsList); topicAdapter = new TopicAdapter(this, topicItems);
recyclerView.setAdapter(topicAdapter); recyclerView.setAdapter(topicAdapter);
replyFAB = findViewById(R.id.topic_fab); replyFAB = findViewById(R.id.topic_fab);
@ -280,15 +280,15 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
} }
return; return;
} else if (viewModel.isWritingReply()) { } else if (viewModel.isWritingReply()) {
postsList.remove(postsList.size() - 1); topicItems.remove(topicItems.size() - 1);
topicAdapter.notifyItemRemoved(postsList.size()); topicAdapter.notifyItemRemoved(topicItems.size());
topicAdapter.setBackButtonHidden(); topicAdapter.setBackButtonHidden();
viewModel.setWritingReply(false); viewModel.setWritingReply(false);
replyFAB.show(); replyFAB.show();
bottomNavBar.setVisibility(View.VISIBLE); bottomNavBar.setVisibility(View.VISIBLE);
return; return;
} else if (viewModel.isEditingPost()) { } else if (viewModel.isEditingPost()) {
postsList.get(viewModel.getPostBeingEditedPosition()).setPostType(Post.TYPE_POST); ((Post) topicItems.get(viewModel.getPostBeingEditedPosition())).setPostType(Post.TYPE_POST);
topicAdapter.notifyItemChanged(viewModel.getPostBeingEditedPosition()); topicAdapter.notifyItemChanged(viewModel.getPostBeingEditedPosition());
topicAdapter.setBackButtonHidden(); topicAdapter.setBackButtonHidden();
viewModel.setEditingPost(false); viewModel.setEditingPost(false);
@ -538,7 +538,7 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
replyFAB.show(); replyFAB.show();
bottomNavBar.setVisibility(View.VISIBLE); bottomNavBar.setVisibility(View.VISIBLE);
viewModel.setWritingReply(false); viewModel.setWritingReply(false);
if ((postsList.get(postsList.size() - 1).getPostNumber() + 1) % 15 == 0) { if ((((Post) topicItems.get(topicItems.size() - 1)).getPostNumber() + 1) % 15 == 0) {
Timber.i("Reply was posted in new page. Switching to last page."); Timber.i("Reply was posted in new page. Switching to last page.");
viewModel.loadUrl(ParseHelpers.getBaseURL(viewModel.getTopicUrl()) + "." + 2147483647); viewModel.loadUrl(ParseHelpers.getBaseURL(viewModel.getTopicUrl()) + "." + 2147483647);
} else { } else {
@ -547,8 +547,8 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
} else { } else {
Timber.w("Post reply unsuccessful"); Timber.w("Post reply unsuccessful");
Toast.makeText(getBaseContext(), "Post failed!", Toast.LENGTH_SHORT).show(); Toast.makeText(getBaseContext(), "Post failed!", Toast.LENGTH_SHORT).show();
recyclerView.getChildAt(postsList.size() - 1).setAlpha(1); recyclerView.getChildAt(topicItems.size() - 1).setAlpha(1);
recyclerView.getChildAt(postsList.size() - 1).setEnabled(true); recyclerView.getChildAt(topicItems.size() - 1).setEnabled(true);
} }
} }
}); });
@ -581,7 +581,7 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
if (result) { if (result) {
Timber.i("Post edit successful"); Timber.i("Post edit successful");
postsList.get(position).setPostType(Post.TYPE_POST); ((Post) topicItems.get(position)).setPostType(Post.TYPE_POST);
topicAdapter.notifyItemChanged(position); topicAdapter.notifyItemChanged(position);
replyFAB.show(); replyFAB.show();
bottomNavBar.setVisibility(View.VISIBLE); bottomNavBar.setVisibility(View.VISIBLE);
@ -631,11 +631,11 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
else else
replyFAB.show(); replyFAB.show();
}); });
viewModel.getPostsList().observe(this, postList -> { viewModel.getTopicItems().observe(this, postList -> {
if (postList == null) progressBar.setVisibility(ProgressBar.VISIBLE); if (postList == null) progressBar.setVisibility(ProgressBar.VISIBLE);
recyclerView.getRecycledViewPool().clear(); //Avoid inconsistency detected bug recyclerView.getRecycledViewPool().clear(); //Avoid inconsistency detected bug
postsList.clear(); topicItems.clear();
postsList.addAll(postList); topicItems.addAll(postList);
topicAdapter.notifyDataSetChanged(); topicAdapter.notifyDataSetChanged();
}); });
/*viewModel.getFocusedPostIndex().observe(this, focusedPostIndex -> { /*viewModel.getFocusedPostIndex().observe(this, focusedPostIndex -> {
@ -652,7 +652,7 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
break; break;
case NETWORK_ERROR: case NETWORK_ERROR:
Timber.w("Network error on loaded page"); Timber.w("Network error on loaded page");
if (viewModel.getPostsList().getValue() == null) { if (viewModel.getTopicItems().getValue() == null) {
// no page has been loaded yet. Give user the ability to refresh // no page has been loaded yet. Give user the ability to refresh
recyclerView.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE);
TextView errorTextview = findViewById(R.id.error_textview); TextView errorTextview = findViewById(R.id.error_textview);
@ -710,9 +710,9 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
Timber.i("Prepare for reply successful"); Timber.i("Prepare for reply successful");
//prepare for a reply //prepare for a reply
viewModel.setWritingReply(true); viewModel.setWritingReply(true);
postsList.add(Post.newQuickReply()); topicItems.add(Post.newQuickReply());
topicAdapter.notifyItemInserted(postsList.size()); topicAdapter.notifyItemInserted(topicItems.size());
recyclerView.scrollToPosition(postsList.size() - 1); recyclerView.scrollToPosition(topicItems.size() - 1);
replyFAB.hide(); replyFAB.hide();
bottomNavBar.setVisibility(View.GONE); bottomNavBar.setVisibility(View.GONE);
} else { } else {
@ -725,7 +725,7 @@ public class TopicActivity extends BaseActivity implements TopicAdapter.OnPostFo
if (result != null && result.isSuccessful()) { if (result != null && result.isSuccessful()) {
Timber.i("Prepare for edit successful"); Timber.i("Prepare for edit successful");
viewModel.setEditingPost(true); viewModel.setEditingPost(true);
postsList.get(result.getPosition()).setPostType(Post.TYPE_EDIT); ((Post) topicItems.get(result.getPosition())).setPostType(Post.TYPE_EDIT);
topicAdapter.notifyItemChanged(result.getPosition()); topicAdapter.notifyItemChanged(result.getPosition());
recyclerView.scrollToPosition(result.getPosition()); recyclerView.scrollToPosition(result.getPosition());
replyFAB.hide(); replyFAB.hide();

779
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java

@ -46,9 +46,11 @@ import gr.thmmy.mthmmy.activities.profile.ProfileActivity;
import gr.thmmy.mthmmy.base.BaseActivity; import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.editorview.EditorView; import gr.thmmy.mthmmy.editorview.EditorView;
import gr.thmmy.mthmmy.editorview.EmojiKeyboard; import gr.thmmy.mthmmy.editorview.EmojiKeyboard;
import gr.thmmy.mthmmy.model.Poll;
import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyFile; import gr.thmmy.mthmmy.model.ThmmyFile;
import gr.thmmy.mthmmy.model.ThmmyPage; import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.model.TopicItem;
import gr.thmmy.mthmmy.utils.CircleTransform; import gr.thmmy.mthmmy.utils.CircleTransform;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers; import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import gr.thmmy.mthmmy.viewmodel.TopicViewModel; import gr.thmmy.mthmmy.viewmodel.TopicViewModel;
@ -76,16 +78,16 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context context; private final Context context;
private final OnPostFocusChangeListener postFocusListener; private final OnPostFocusChangeListener postFocusListener;
private final EmojiKeyboard.EmojiKeyboardOwner emojiKeyboardOwner; private final EmojiKeyboard.EmojiKeyboardOwner emojiKeyboardOwner;
private final List<Post> postsList; private final List<TopicItem> topicItems;
private TopicViewModel viewModel; private TopicViewModel viewModel;
/** /**
* @param context the context of the {@link RecyclerView} * @param context the context of the {@link RecyclerView}
* @param postsList List of {@link Post} objects to use * @param topicItems List of {@link Post} objects to use
*/ */
TopicAdapter(TopicActivity context, List<Post> postsList) { TopicAdapter(TopicActivity context, List<TopicItem> topicItems) {
this.context = context; this.context = context;
this.postsList = postsList; this.topicItems = topicItems;
this.postFocusListener = context; this.postFocusListener = context;
this.emojiKeyboardOwner = context; this.emojiKeyboardOwner = context;
@ -96,7 +98,8 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@Override @Override
public int getItemViewType(int position) { public int getItemViewType(int position) {
return postsList.get(position).getPostType(); if (topicItems.get(position) instanceof Poll) return Poll.TYPE_POLL;
return ((Post) topicItems.get(position)).getPostType();
} }
@NonNull @NonNull
@ -141,414 +144,418 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
@Override @Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder currentHolder, public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder currentHolder,
final int position) { final int position) {
if (currentHolder instanceof PostViewHolder) { if (currentHolder.getItemViewType() == Poll.TYPE_POLL) {
final Post currentPost = postsList.get(position);
final PostViewHolder holder = (PostViewHolder) currentHolder; } else {
Post currentPost = (Post) topicItems.get(position);
//Post's WebView parameters if (currentHolder instanceof PostViewHolder) {
holder.post.setClickable(true); final PostViewHolder holder = (PostViewHolder) currentHolder;
holder.post.setWebViewClient(new LinkLauncher());
//Post's WebView parameters
//Avoids errors about layout having 0 width/height holder.post.setClickable(true);
holder.thumbnail.setMinimumWidth(1); holder.post.setWebViewClient(new LinkLauncher());
holder.thumbnail.setMinimumHeight(1);
//Sets thumbnail size //Avoids errors about layout having 0 width/height
holder.thumbnail.setMaxWidth(THUMBNAIL_SIZE); holder.thumbnail.setMinimumWidth(1);
holder.thumbnail.setMaxHeight(THUMBNAIL_SIZE); holder.thumbnail.setMinimumHeight(1);
//Sets thumbnail size
//noinspection ConstantConditions holder.thumbnail.setMaxWidth(THUMBNAIL_SIZE);
Picasso.with(context) holder.thumbnail.setMaxHeight(THUMBNAIL_SIZE);
.load(currentPost.getThumbnailURL())
.resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE) //noinspection ConstantConditions
.centerCrop() Picasso.with(context)
.error(ResourcesCompat.getDrawable(context.getResources() .load(currentPost.getThumbnailURL())
, R.drawable.ic_default_user_thumbnail_white_24dp, null)) .resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
.placeholder(ResourcesCompat.getDrawable(context.getResources() .centerCrop()
, R.drawable.ic_default_user_thumbnail_white_24dp, null)) .error(ResourcesCompat.getDrawable(context.getResources()
.transform(new CircleTransform()) , R.drawable.ic_default_user_thumbnail_white_24dp, null))
.into(holder.thumbnail); .placeholder(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
//Sets username,submit date, index number, subject, post's and attached files texts .transform(new CircleTransform())
holder.username.setText(currentPost.getAuthor()); .into(holder.thumbnail);
holder.postDate.setText(currentPost.getPostDate());
if (currentPost.getPostNumber() != 0) //Sets username,submit date, index number, subject, post's and attached files texts
holder.postNum.setText(context.getString( holder.username.setText(currentPost.getAuthor());
R.string.user_number_of_posts, currentPost.getPostNumber())); holder.postDate.setText(currentPost.getPostDate());
else if (currentPost.getPostNumber() != 0)
holder.postNum.setText(""); holder.postNum.setText(context.getString(
holder.subject.setText(currentPost.getSubject()); R.string.user_number_of_posts, currentPost.getPostNumber()));
holder.post.loadDataWithBaseURL("file:///android_asset/", currentPost.getContent(), "text/html", "UTF-8", null); else
if ((currentPost.getAttachedFiles() != null && currentPost.getAttachedFiles().size() != 0) holder.postNum.setText("");
|| (currentPost.getLastEdit() != null)) { holder.subject.setText(currentPost.getSubject());
holder.bodyFooterDivider.setVisibility(View.VISIBLE); holder.post.loadDataWithBaseURL("file:///android_asset/", currentPost.getContent(), "text/html", "UTF-8", null);
holder.postFooter.removeAllViews(); if ((currentPost.getAttachedFiles() != null && currentPost.getAttachedFiles().size() != 0)
|| (currentPost.getLastEdit() != null)) {
if (currentPost.getAttachedFiles() != null && currentPost.getAttachedFiles().size() != 0) { holder.bodyFooterDivider.setVisibility(View.VISIBLE);
int filesTextColor; holder.postFooter.removeAllViews();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
filesTextColor = context.getResources().getColor(R.color.accent, null); if (currentPost.getAttachedFiles() != null && currentPost.getAttachedFiles().size() != 0) {
} else //noinspection deprecation int filesTextColor;
filesTextColor = context.getResources().getColor(R.color.accent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
filesTextColor = context.getResources().getColor(R.color.accent, null);
for (final ThmmyFile attachedFile : currentPost.getAttachedFiles()) { } else //noinspection deprecation
final TextView attached = new TextView(context); filesTextColor = context.getResources().getColor(R.color.accent);
attached.setTextSize(10f);
attached.setClickable(true); for (final ThmmyFile attachedFile : currentPost.getAttachedFiles()) {
attached.setTypeface(Typeface.createFromAsset(context.getAssets() final TextView attached = new TextView(context);
, "fonts/fontawesome-webfont.ttf")); attached.setTextSize(10f);
attached.setText(faIconFromFilename(attachedFile.getFilename()) + " " attached.setClickable(true);
+ attachedFile.getFilename() + attachedFile.getFileInfo()); attached.setTypeface(Typeface.createFromAsset(context.getAssets()
attached.setTextColor(filesTextColor); , "fonts/fontawesome-webfont.ttf"));
attached.setPadding(0, 3, 0, 3); attached.setText(faIconFromFilename(attachedFile.getFilename()) + " "
+ attachedFile.getFilename() + attachedFile.getFileInfo());
attached.setOnClickListener(view -> ((BaseActivity) context).downloadFile(attachedFile)); attached.setTextColor(filesTextColor);
attached.setPadding(0, 3, 0, 3);
holder.postFooter.addView(attached);
attached.setOnClickListener(view -> ((BaseActivity) context).downloadFile(attachedFile));
holder.postFooter.addView(attached);
}
} }
if (currentPost.getLastEdit() != null && currentPost.getLastEdit().length() > 0) {
int lastEditTextColor;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
lastEditTextColor = context.getResources().getColor(R.color.white, null);
} else //noinspection deprecation
lastEditTextColor = context.getResources().getColor(R.color.white);
final TextView lastEdit = new TextView(context);
lastEdit.setTextSize(12f);
lastEdit.setText(currentPost.getLastEdit());
lastEdit.setTextColor(lastEditTextColor);
lastEdit.setPadding(0, 3, 0, 3);
holder.postFooter.addView(lastEdit);
}
} else {
holder.bodyFooterDivider.setVisibility(View.GONE);
holder.postFooter.removeAllViews();
} }
if (currentPost.getLastEdit() != null && currentPost.getLastEdit().length() > 0) {
int lastEditTextColor;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
lastEditTextColor = context.getResources().getColor(R.color.white, null);
} else //noinspection deprecation
lastEditTextColor = context.getResources().getColor(R.color.white);
final TextView lastEdit = new TextView(context);
lastEdit.setTextSize(12f);
lastEdit.setText(currentPost.getLastEdit());
lastEdit.setTextColor(lastEditTextColor);
lastEdit.setPadding(0, 3, 0, 3);
holder.postFooter.addView(lastEdit);
}
} else {
holder.bodyFooterDivider.setVisibility(View.GONE);
holder.postFooter.removeAllViews();
}
String mSpecialRank, mRank, mGender, mNumberOfPosts, mPersonalText; String mSpecialRank, mRank, mGender, mNumberOfPosts, mPersonalText;
int mNumberOfStars, mUserColor; int mNumberOfStars, mUserColor;
if (!currentPost.isDeleted()) { //Sets user's extra info
mSpecialRank = currentPost.getSpecialRank();
mRank = currentPost.getRank();
mGender = currentPost.getGender();
mNumberOfPosts = currentPost.getNumberOfPosts();
mPersonalText = currentPost.getPersonalText();
mNumberOfStars = currentPost.getNumberOfStars();
} else {
mSpecialRank = null;
mRank = null;
mGender = null;
mNumberOfPosts = null;
mPersonalText = null;
mNumberOfStars = 0;
}
mUserColor = currentPost.getUserColor();
if (!Objects.equals(mSpecialRank, "") && mSpecialRank != null) {
holder.specialRank.setText(mSpecialRank);
holder.specialRank.setVisibility(View.VISIBLE);
} else
holder.specialRank.setVisibility(View.GONE);
if (!Objects.equals(mRank, "") && mRank != null) {
holder.rank.setText(mRank);
holder.rank.setVisibility(View.VISIBLE);
} else
holder.rank.setVisibility(View.GONE);
if (!Objects.equals(mGender, "") && mGender != null) {
holder.gender.setText(mGender);
holder.gender.setVisibility(View.VISIBLE);
} else
holder.gender.setVisibility(View.GONE);
if (!Objects.equals(mNumberOfPosts, "") && mNumberOfPosts != null) {
holder.numberOfPosts.setText(mNumberOfPosts);
holder.numberOfPosts.setVisibility(View.VISIBLE);
} else
holder.numberOfPosts.setVisibility(View.GONE);
if (!Objects.equals(mPersonalText, "") && mPersonalText != null) {
holder.personalText.setText("\"" + mPersonalText + "\"");
holder.personalText.setVisibility(View.VISIBLE);
} else
holder.personalText.setVisibility(View.GONE);
if (mUserColor != USER_COLOR_YELLOW) {
holder.username.setTextColor(mUserColor);
} else {
holder.username.setTextColor(USER_COLOR_WHITE);
}
if (mNumberOfStars > 0) {
holder.stars.setTypeface(Typeface.createFromAsset(context.getAssets()
, "fonts/fontawesome-webfont.ttf"));
String aStar = context.getResources().getString(R.string.fa_icon_star);
StringBuilder usersStars = new StringBuilder();
for (int i = 0; i < mNumberOfStars; ++i) {
usersStars.append(aStar);
}
holder.stars.setText(usersStars.toString());
holder.stars.setTextColor(mUserColor);
holder.stars.setVisibility(View.VISIBLE);
} else
holder.stars.setVisibility(View.GONE);
if (currentPost.isUserMentionedInPost()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.mention_card, null));
} else //noinspection deprecation
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.mention_card));
} else if (mUserColor == TopicParser.USER_COLOR_PINK) {
//Special card for special member of the month!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.member_of_the_month_card, null));
} else //noinspection deprecation
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.member_of_the_month_card));
} else holder.cardChildLinear.setBackground(null);
//Avoid's view's visibility recycling
if (!currentPost.isDeleted() && viewModel.isUserExtraInfoVisible(holder.getAdapterPosition())) {
holder.userExtraInfo.setVisibility(View.VISIBLE);
holder.userExtraInfo.setAlpha(1.0f);
holder.username.setMaxLines(Integer.MAX_VALUE);
holder.username.setEllipsize(null);
holder.subject.setTextColor(Color.parseColor("#FFFFFF"));
holder.subject.setMaxLines(Integer.MAX_VALUE);
holder.subject.setEllipsize(null);
} else {
holder.userExtraInfo.setVisibility(View.GONE);
holder.userExtraInfo.setAlpha(0.0f);
holder.username.setMaxLines(1);
holder.username.setEllipsize(TextUtils.TruncateAt.END);
holder.subject.setTextColor(Color.parseColor("#757575"));
holder.subject.setMaxLines(1);
holder.subject.setEllipsize(TextUtils.TruncateAt.END);
}
if (!currentPost.isDeleted()) {
//Sets graphics behavior
holder.thumbnail.setOnClickListener(view -> {
//Clicking the thumbnail opens user's profile
Intent intent = new Intent(context, ProfileActivity.class);
Bundle extras = new Bundle();
extras.putString(BUNDLE_PROFILE_URL, currentPost.getProfileURL());
if (currentPost.getThumbnailURL() == null)
extras.putString(BUNDLE_PROFILE_THUMBNAIL_URL, "");
else
extras.putString(BUNDLE_PROFILE_THUMBNAIL_URL, currentPost.getThumbnailURL());
extras.putString(BUNDLE_PROFILE_USERNAME, currentPost.getAuthor());
intent.putExtras(extras);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
});
holder.header.setOnClickListener(v -> {
//Clicking the header makes it expand/collapse
viewModel.toggleUserInfo(holder.getAdapterPosition());
TopicAnimations.animateUserExtraInfoVisibility(holder.username,
holder.subject, Color.parseColor("#FFFFFF"),
Color.parseColor("#757575"), holder.userExtraInfo);
});
//Clicking the expanded part of a header (the extra info) makes it collapse
holder.userExtraInfo.setOnClickListener(v -> {
viewModel.hideUserInfo(holder.getAdapterPosition());
TopicAnimations.animateUserExtraInfoVisibility(holder.username,
holder.subject, Color.parseColor("#FFFFFF"),
Color.parseColor("#757575"), (LinearLayout) v);
});
} else {
holder.header.setOnClickListener(null);
holder.userExtraInfo.setOnClickListener(null);
}
holder.overflowButton.setOnClickListener(view -> { if (!currentPost.isDeleted()) { //Sets user's extra info
//Inflates the popup menu content mSpecialRank = currentPost.getSpecialRank();
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRank = currentPost.getRank();
if (layoutInflater == null) { mGender = currentPost.getGender();
return; mNumberOfPosts = currentPost.getNumberOfPosts();
mPersonalText = currentPost.getPersonalText();
mNumberOfStars = currentPost.getNumberOfStars();
} else {
mSpecialRank = null;
mRank = null;
mGender = null;
mNumberOfPosts = null;
mPersonalText = null;
mNumberOfStars = 0;
} }
View popUpContent = layoutInflater.inflate(R.layout.activity_topic_overflow_menu, null); mUserColor = currentPost.getUserColor();
//Creates the PopupWindow if (!Objects.equals(mSpecialRank, "") && mSpecialRank != null) {
final PopupWindow popUp = new PopupWindow(holder.overflowButton.getContext()); holder.specialRank.setText(mSpecialRank);
popUp.setContentView(popUpContent); holder.specialRank.setVisibility(View.VISIBLE);
popUp.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT); } else
popUp.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT); holder.specialRank.setVisibility(View.GONE);
popUp.setFocusable(true); if (!Objects.equals(mRank, "") && mRank != null) {
holder.rank.setText(mRank);
TextView shareButton = popUpContent.findViewById(R.id.post_share_button); holder.rank.setVisibility(View.VISIBLE);
Drawable shareStartDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_share_white_24dp); } else
shareButton.setCompoundDrawablesRelativeWithIntrinsicBounds(shareStartDrawable, null, null, null); holder.rank.setVisibility(View.GONE);
shareButton.setOnClickListener(v -> { if (!Objects.equals(mGender, "") && mGender != null) {
Intent sendIntent = new Intent(Intent.ACTION_SEND); holder.gender.setText(mGender);
sendIntent.setType("text/plain"); holder.gender.setVisibility(View.VISIBLE);
sendIntent.putExtra(Intent.EXTRA_TEXT, currentPost.getPostURL()); } else
context.startActivity(Intent.createChooser(sendIntent, "Share via")); holder.gender.setVisibility(View.GONE);
popUp.dismiss(); if (!Objects.equals(mNumberOfPosts, "") && mNumberOfPosts != null) {
}); holder.numberOfPosts.setText(mNumberOfPosts);
holder.numberOfPosts.setVisibility(View.VISIBLE);
} else
holder.numberOfPosts.setVisibility(View.GONE);
if (!Objects.equals(mPersonalText, "") && mPersonalText != null) {
holder.personalText.setText("\"" + mPersonalText + "\"");
holder.personalText.setVisibility(View.VISIBLE);
} else
holder.personalText.setVisibility(View.GONE);
if (mUserColor != USER_COLOR_YELLOW) {
holder.username.setTextColor(mUserColor);
} else {
holder.username.setTextColor(USER_COLOR_WHITE);
}
if (mNumberOfStars > 0) {
holder.stars.setTypeface(Typeface.createFromAsset(context.getAssets()
, "fonts/fontawesome-webfont.ttf"));
String aStar = context.getResources().getString(R.string.fa_icon_star);
StringBuilder usersStars = new StringBuilder();
for (int i = 0; i < mNumberOfStars; ++i) {
usersStars.append(aStar);
}
holder.stars.setText(usersStars.toString());
holder.stars.setTextColor(mUserColor);
holder.stars.setVisibility(View.VISIBLE);
} else
holder.stars.setVisibility(View.GONE);
if (currentPost.isUserMentionedInPost()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.mention_card, null));
} else //noinspection deprecation
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.mention_card));
} else if (mUserColor == TopicParser.USER_COLOR_PINK) {
//Special card for special member of the month!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.member_of_the_month_card, null));
} else //noinspection deprecation
holder.cardChildLinear.setBackground(context.getResources().
getDrawable(R.drawable.member_of_the_month_card));
} else holder.cardChildLinear.setBackground(null);
final TextView editPostButton = popUpContent.findViewById(R.id.edit_post); //Avoid's view's visibility recycling
Drawable editStartDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_edit_white_24dp); if (!currentPost.isDeleted() && viewModel.isUserExtraInfoVisible(holder.getAdapterPosition())) {
editPostButton.setCompoundDrawablesRelativeWithIntrinsicBounds(editStartDrawable, null, null, null); holder.userExtraInfo.setVisibility(View.VISIBLE);
holder.userExtraInfo.setAlpha(1.0f);
if (viewModel.isEditingPost() || currentPost.getPostEditURL() == null || currentPost.getPostEditURL().equals("")) { holder.username.setMaxLines(Integer.MAX_VALUE);
editPostButton.setVisibility(View.GONE); holder.username.setEllipsize(null);
holder.subject.setTextColor(Color.parseColor("#FFFFFF"));
holder.subject.setMaxLines(Integer.MAX_VALUE);
holder.subject.setEllipsize(null);
} else { } else {
editPostButton.setOnClickListener(v -> { holder.userExtraInfo.setVisibility(View.GONE);
viewModel.prepareForEdit(position, postsList.get(position).getPostEditURL()); holder.userExtraInfo.setAlpha(0.0f);
popUp.dismiss();
});
}
TextView deletePostButton = popUpContent.findViewById(R.id.delete_post); holder.username.setMaxLines(1);
holder.username.setEllipsize(TextUtils.TruncateAt.END);
if (currentPost.getPostDeleteURL() == null || currentPost.getPostDeleteURL().equals("")) { holder.subject.setTextColor(Color.parseColor("#757575"));
deletePostButton.setVisibility(View.GONE); holder.subject.setMaxLines(1);
holder.subject.setEllipsize(TextUtils.TruncateAt.END);
}
if (!currentPost.isDeleted()) {
//Sets graphics behavior
holder.thumbnail.setOnClickListener(view -> {
//Clicking the thumbnail opens user's profile
Intent intent = new Intent(context, ProfileActivity.class);
Bundle extras = new Bundle();
extras.putString(BUNDLE_PROFILE_URL, currentPost.getProfileURL());
if (currentPost.getThumbnailURL() == null)
extras.putString(BUNDLE_PROFILE_THUMBNAIL_URL, "");
else
extras.putString(BUNDLE_PROFILE_THUMBNAIL_URL, currentPost.getThumbnailURL());
extras.putString(BUNDLE_PROFILE_USERNAME, currentPost.getAuthor());
intent.putExtras(extras);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
});
holder.header.setOnClickListener(v -> {
//Clicking the header makes it expand/collapse
viewModel.toggleUserInfo(holder.getAdapterPosition());
TopicAnimations.animateUserExtraInfoVisibility(holder.username,
holder.subject, Color.parseColor("#FFFFFF"),
Color.parseColor("#757575"), holder.userExtraInfo);
});
//Clicking the expanded part of a header (the extra info) makes it collapse
holder.userExtraInfo.setOnClickListener(v -> {
viewModel.hideUserInfo(holder.getAdapterPosition());
TopicAnimations.animateUserExtraInfoVisibility(holder.username,
holder.subject, Color.parseColor("#FFFFFF"),
Color.parseColor("#757575"), (LinearLayout) v);
});
} else { } else {
Drawable deleteStartDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_delete_white_24dp); holder.header.setOnClickListener(null);
deletePostButton.setCompoundDrawablesRelativeWithIntrinsicBounds(deleteStartDrawable, null, null, null); holder.userExtraInfo.setOnClickListener(null);
popUpContent.findViewById(R.id.delete_post).setOnClickListener(v -> { }
new AlertDialog.Builder(holder.overflowButton.getContext())
.setTitle("Delete post") holder.overflowButton.setOnClickListener(view -> {
.setMessage("Do you really want to delete this post?") //Inflates the popup menu content
.setIcon(android.R.drawable.ic_dialog_alert) LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> viewModel.deletePost(currentPost.getPostDeleteURL())) if (layoutInflater == null) {
.setNegativeButton(android.R.string.no, null).show(); return;
}
View popUpContent = layoutInflater.inflate(R.layout.activity_topic_overflow_menu, null);
//Creates the PopupWindow
final PopupWindow popUp = new PopupWindow(holder.overflowButton.getContext());
popUp.setContentView(popUpContent);
popUp.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
popUp.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
popUp.setFocusable(true);
TextView shareButton = popUpContent.findViewById(R.id.post_share_button);
Drawable shareStartDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_share_white_24dp);
shareButton.setCompoundDrawablesRelativeWithIntrinsicBounds(shareStartDrawable, null, null, null);
shareButton.setOnClickListener(v -> {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, currentPost.getPostURL());
context.startActivity(Intent.createChooser(sendIntent, "Share via"));
popUp.dismiss(); popUp.dismiss();
}); });
}
//Displays the popup final TextView editPostButton = popUpContent.findViewById(R.id.edit_post);
popUp.showAsDropDown(holder.overflowButton); Drawable editStartDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_edit_white_24dp);
}); editPostButton.setCompoundDrawablesRelativeWithIntrinsicBounds(editStartDrawable, null, null, null);
if (viewModel.isEditingPost() || currentPost.getPostEditURL() == null || currentPost.getPostEditURL().equals("")) {
editPostButton.setVisibility(View.GONE);
} else {
editPostButton.setOnClickListener(v -> {
viewModel.prepareForEdit(position, currentPost.getPostEditURL());
popUp.dismiss();
});
}
//noinspection PointlessBooleanExpression,ConstantConditions TextView deletePostButton = popUpContent.findViewById(R.id.delete_post);
if (!BaseActivity.getSessionManager().isLoggedIn() || !viewModel.canReply()) {
holder.quoteToggle.setVisibility(View.GONE); if (currentPost.getPostDeleteURL() == null || currentPost.getPostDeleteURL().equals("")) {
} else { deletePostButton.setVisibility(View.GONE);
if (viewModel.getToQuoteList().contains(currentPost.getPostIndex())) } else {
holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_checked_accent_24dp); Drawable deleteStartDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_delete_white_24dp);
else deletePostButton.setCompoundDrawablesRelativeWithIntrinsicBounds(deleteStartDrawable, null, null, null);
holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_unchecked_24dp); popUpContent.findViewById(R.id.delete_post).setOnClickListener(v -> {
//Sets graphics behavior new AlertDialog.Builder(holder.overflowButton.getContext())
holder.quoteToggle.setOnClickListener(view -> { .setTitle("Delete post")
viewModel.postIndexToggle(currentPost.getPostIndex()); .setMessage("Do you really want to delete this post?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> viewModel.deletePost(currentPost.getPostDeleteURL()))
.setNegativeButton(android.R.string.no, null).show();
popUp.dismiss();
});
}
//Displays the popup
popUp.showAsDropDown(holder.overflowButton);
});
//noinspection PointlessBooleanExpression,ConstantConditions
if (!BaseActivity.getSessionManager().isLoggedIn() || !viewModel.canReply()) {
holder.quoteToggle.setVisibility(View.GONE);
} else {
if (viewModel.getToQuoteList().contains(currentPost.getPostIndex())) if (viewModel.getToQuoteList().contains(currentPost.getPostIndex()))
holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_checked_accent_24dp); holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_checked_accent_24dp);
else else
holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_unchecked_24dp); holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_unchecked_24dp);
}); //Sets graphics behavior
} holder.quoteToggle.setOnClickListener(view -> {
} else if (currentHolder instanceof QuickReplyViewHolder) { viewModel.postIndexToggle(currentPost.getPostIndex());
final QuickReplyViewHolder holder = (QuickReplyViewHolder) currentHolder; if (viewModel.getToQuoteList().contains(currentPost.getPostIndex()))
holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_checked_accent_24dp);
//noinspection ConstantConditions else
Picasso.with(context) holder.quoteToggle.setImageResource(R.drawable.ic_format_quote_unchecked_24dp);
.load(getSessionManager().getAvatarLink()) });
.resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
.centerCrop()
.error(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.placeholder(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.transform(new CircleTransform())
.into(holder.thumbnail);
holder.username.setText(getSessionManager().getUsername());
holder.quickReplySubject.setText("Re: " + viewModel.getTopicTitle().getValue());
holder.quickReplySubject.setRawInputType(InputType.TYPE_CLASS_TEXT);
holder.quickReplySubject.setImeOptions(EditorInfo.IME_ACTION_DONE);
holder.replyEditor.setEmojiKeyboardOwner(emojiKeyboardOwner);
InputConnection ic = holder.replyEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic);
holder.replyEditor.updateEmojiKeyboardVisibility();
holder.replyEditor.getEditText().setOnFocusChangeListener((v, hasFocus) -> {
InputConnection ic12 = holder.replyEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic12);
holder.replyEditor.updateEmojiKeyboardVisibility();
});
holder.replyEditor.setText(viewModel.getBuildedQuotes());
holder.replyEditor.setOnSubmitListener(view -> {
if (holder.quickReplySubject.getText().toString().isEmpty()) return;
if (holder.replyEditor.getText().toString().isEmpty()) {
holder.replyEditor.setError("Required");
return;
}
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
holder.itemView.setAlpha(0.5f);
holder.itemView.setEnabled(false);
emojiKeyboardOwner.setEmojiKeyboardVisible(false);
viewModel.postReply(context, holder.quickReplySubject.getText().toString(),
holder.replyEditor.getText().toString());
});
holder.replyEditor.setOnClickListener(view -> holder.replyEditor.setError(null));
if (backPressHidden) {
holder.replyEditor.requestFocus();
backPressHidden = false;
}
} else if (currentHolder instanceof EditMessageViewHolder) {
final EditMessageViewHolder holder = (EditMessageViewHolder) currentHolder;
//noinspection ConstantConditions
Picasso.with(context)
.load(getSessionManager().getAvatarLink())
.resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
.centerCrop()
.error(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.placeholder(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.transform(new CircleTransform())
.into(holder.thumbnail);
holder.username.setText(getSessionManager().getUsername());
holder.editSubject.setText(postsList.get(position).getSubject());
holder.editSubject.setRawInputType(InputType.TYPE_CLASS_TEXT);
holder.editSubject.setImeOptions(EditorInfo.IME_ACTION_DONE);
holder.editEditor.setEmojiKeyboardOwner(emojiKeyboardOwner);
InputConnection ic = holder.editEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic);
holder.editEditor.updateEmojiKeyboardVisibility();
holder.editEditor.setText(viewModel.getPostBeingEditedText());
holder.editEditor.getEditText().setOnFocusChangeListener((v, hasFocus) -> {
if (hasFocus) {
InputConnection ic1 = holder.editEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic1);
holder.editEditor.updateEmojiKeyboardVisibility();
} }
}); } else if (currentHolder instanceof QuickReplyViewHolder) {
holder.editEditor.setOnSubmitListener(view -> { final QuickReplyViewHolder holder = (QuickReplyViewHolder) currentHolder;
if (holder.editSubject.getText().toString().isEmpty()) return;
if (holder.editEditor.getText().toString().isEmpty()) { //noinspection ConstantConditions
holder.editEditor.setError("Required"); Picasso.with(context)
return; .load(getSessionManager().getAvatarLink())
.resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
.centerCrop()
.error(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.placeholder(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.transform(new CircleTransform())
.into(holder.thumbnail);
holder.username.setText(getSessionManager().getUsername());
holder.quickReplySubject.setText("Re: " + viewModel.getTopicTitle().getValue());
holder.quickReplySubject.setRawInputType(InputType.TYPE_CLASS_TEXT);
holder.quickReplySubject.setImeOptions(EditorInfo.IME_ACTION_DONE);
holder.replyEditor.setEmojiKeyboardOwner(emojiKeyboardOwner);
InputConnection ic = holder.replyEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic);
holder.replyEditor.updateEmojiKeyboardVisibility();
holder.replyEditor.getEditText().setOnFocusChangeListener((v, hasFocus) -> {
InputConnection ic12 = holder.replyEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic12);
holder.replyEditor.updateEmojiKeyboardVisibility();
});
holder.replyEditor.setText(viewModel.getBuildedQuotes());
holder.replyEditor.setOnSubmitListener(view -> {
if (holder.quickReplySubject.getText().toString().isEmpty()) return;
if (holder.replyEditor.getText().toString().isEmpty()) {
holder.replyEditor.setError("Required");
return;
}
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
holder.itemView.setAlpha(0.5f);
holder.itemView.setEnabled(false);
emojiKeyboardOwner.setEmojiKeyboardVisible(false);
viewModel.postReply(context, holder.quickReplySubject.getText().toString(),
holder.replyEditor.getText().toString());
});
holder.replyEditor.setOnClickListener(view -> holder.replyEditor.setError(null));
if (backPressHidden) {
holder.replyEditor.requestFocus();
backPressHidden = false;
} }
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); } else if (currentHolder instanceof EditMessageViewHolder) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); final EditMessageViewHolder holder = (EditMessageViewHolder) currentHolder;
holder.itemView.setAlpha(0.5f);
holder.itemView.setEnabled(false); //noinspection ConstantConditions
emojiKeyboardOwner.setEmojiKeyboardVisible(false); Picasso.with(context)
.load(getSessionManager().getAvatarLink())
.resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE)
.centerCrop()
.error(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.placeholder(ResourcesCompat.getDrawable(context.getResources()
, R.drawable.ic_default_user_thumbnail_white_24dp, null))
.transform(new CircleTransform())
.into(holder.thumbnail);
holder.username.setText(getSessionManager().getUsername());
holder.editSubject.setText(currentPost.getSubject());
holder.editSubject.setRawInputType(InputType.TYPE_CLASS_TEXT);
holder.editSubject.setImeOptions(EditorInfo.IME_ACTION_DONE);
holder.editEditor.setEmojiKeyboardOwner(emojiKeyboardOwner);
InputConnection ic = holder.editEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic);
holder.editEditor.updateEmojiKeyboardVisibility();
holder.editEditor.setText(viewModel.getPostBeingEditedText());
holder.editEditor.getEditText().setOnFocusChangeListener((v, hasFocus) -> {
if (hasFocus) {
InputConnection ic1 = holder.editEditor.getInputConnection();
emojiKeyboardOwner.setEmojiKeyboardInputConnection(ic1);
holder.editEditor.updateEmojiKeyboardVisibility();
}
});
holder.editEditor.setOnSubmitListener(view -> {
if (holder.editSubject.getText().toString().isEmpty()) return;
if (holder.editEditor.getText().toString().isEmpty()) {
holder.editEditor.setError("Required");
return;
}
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
holder.itemView.setAlpha(0.5f);
holder.itemView.setEnabled(false);
emojiKeyboardOwner.setEmojiKeyboardVisible(false);
viewModel.editPost(position, holder.editSubject.getText().toString(), holder.editEditor.getText().toString()); viewModel.editPost(position, holder.editSubject.getText().toString(), holder.editEditor.getText().toString());
}); });
if (backPressHidden) { if (backPressHidden) {
holder.editEditor.requestFocus(); holder.editEditor.requestFocus();
backPressHidden = false; backPressHidden = false;
}
} }
} }
} }
@Override @Override
public int getItemCount() { public int getItemCount() {
return postsList.size(); return topicItems.size();
} }
/** /**
@ -680,8 +687,8 @@ class TopicAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
if (tmpUrlSbstr.contains("msg")) if (tmpUrlSbstr.contains("msg"))
tmpUrlSbstr = tmpUrlSbstr.substring(0, tmpUrlSbstr.indexOf("msg") - 1); tmpUrlSbstr = tmpUrlSbstr.substring(0, tmpUrlSbstr.indexOf("msg") - 1);
int testAgainst = Integer.parseInt(tmpUrlSbstr); int testAgainst = Integer.parseInt(tmpUrlSbstr);
for (int i = 0; i < postsList.size(); i++) { for (int i = 0; i < topicItems.size(); i++) {
if (postsList.get(i).getPostIndex() == testAgainst) { if (topicItems.get(i) instanceof Post && ((Post) topicItems.get(i)).getPostIndex() == testAgainst) {
//same page //same page
Timber.e(Integer.toString(i)); Timber.e(Integer.toString(i));
postFocusListener.onPostFocusChange(i); postFocusListener.onPostFocusChange(i);

5
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicParser.java

@ -18,6 +18,7 @@ import java.util.regex.Pattern;
import gr.thmmy.mthmmy.base.BaseActivity; import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyFile; import gr.thmmy.mthmmy.model.ThmmyFile;
import gr.thmmy.mthmmy.model.TopicItem;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers; import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import timber.log.Timber; import timber.log.Timber;
@ -146,10 +147,10 @@ public class TopicParser {
* @return {@link ArrayList} of {@link Post}s * @return {@link ArrayList} of {@link Post}s
* @see org.jsoup.Jsoup Jsoup * @see org.jsoup.Jsoup Jsoup
*/ */
public static ArrayList<Post> parseTopic(Document topic, ParseHelpers.Language language) { public static ArrayList<TopicItem> parseTopic(Document topic, ParseHelpers.Language language) {
//Method's variables //Method's variables
final int NO_INDEX = -1; final int NO_INDEX = -1;
ArrayList<Post> parsedPostsList = new ArrayList<>(); ArrayList<TopicItem> parsedPostsList = new ArrayList<>();
Elements postRows; Elements postRows;
//Each row is a post //Each row is a post

5
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTask.java

@ -13,6 +13,7 @@ import gr.thmmy.mthmmy.activities.topic.TopicParser;
import gr.thmmy.mthmmy.base.BaseApplication; import gr.thmmy.mthmmy.base.BaseApplication;
import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyPage; import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.model.TopicItem;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers; import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.Response; import okhttp3.Response;
@ -92,14 +93,14 @@ public class TopicTask extends AsyncTask<String, Void, TopicTaskResult> {
//Finds number of pages //Finds number of pages
int pageCount = TopicParser.parseTopicNumberOfPages(topic, currentPageIndex, language); int pageCount = TopicParser.parseTopicNumberOfPages(topic, currentPageIndex, language);
ArrayList<Post> newPostsList = TopicParser.parseTopic(topic, language); ArrayList<TopicItem> newPostsList = TopicParser.parseTopic(topic, language);
int loadedPageTopicId = Integer.parseInt(ThmmyPage.getTopicId(newPageUrl)); int loadedPageTopicId = Integer.parseInt(ThmmyPage.getTopicId(newPageUrl));
//Finds the position of the focused message if present //Finds the position of the focused message if present
int focusedPostIndex = 0; int focusedPostIndex = 0;
for (int i = 0; i < newPostsList.size(); ++i) { for (int i = 0; i < newPostsList.size(); ++i) {
if (newPostsList.get(i).getPostIndex() == postFocus) { if (newPostsList.get(i) instanceof Post && ((Post) newPostsList.get(i)).getPostIndex() == postFocus) {
focusedPostIndex = i; focusedPostIndex = i;
break; break;
} }

7
app/src/main/java/gr/thmmy/mthmmy/activities/topic/tasks/TopicTaskResult.java

@ -3,6 +3,7 @@ package gr.thmmy.mthmmy.activities.topic.tasks;
import java.util.ArrayList; import java.util.ArrayList;
import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.TopicItem;
public class TopicTaskResult { public class TopicTaskResult {
private final TopicTask.ResultCode resultCode; private final TopicTask.ResultCode resultCode;
@ -16,7 +17,7 @@ public class TopicTaskResult {
* This topic's reply url * This topic's reply url
*/ */
private final String replyPageUrl; private final String replyPageUrl;
private final ArrayList<Post> newPostsList; private final ArrayList<TopicItem> newPostsList;
/** /**
* The topicId of the loaded page * The topicId of the loaded page
*/ */
@ -38,7 +39,7 @@ public class TopicTaskResult {
private final String topicViewers; private final String topicViewers;
public TopicTaskResult(TopicTask.ResultCode resultCode, String topicTitle, public TopicTaskResult(TopicTask.ResultCode resultCode, String topicTitle,
String replyPageUrl, ArrayList<Post> newPostsList, int loadedPageTopicId, String replyPageUrl, ArrayList<TopicItem> newPostsList, int loadedPageTopicId,
int currentPageIndex, int pageCount, int focusedPostIndex, String topicTreeAndMods, int currentPageIndex, int pageCount, int focusedPostIndex, String topicTreeAndMods,
String topicViewers) { String topicViewers) {
this.resultCode = resultCode; this.resultCode = resultCode;
@ -65,7 +66,7 @@ public class TopicTaskResult {
return replyPageUrl; return replyPageUrl;
} }
public ArrayList<Post> getNewPostsList() { public ArrayList<TopicItem> getNewPostsList() {
return newPostsList; return newPostsList;
} }

4
app/src/main/java/gr/thmmy/mthmmy/model/Poll.java

@ -2,7 +2,9 @@ package gr.thmmy.mthmmy.model;
import java.text.DecimalFormat; import java.text.DecimalFormat;
public class Poll { public class Poll extends TopicItem {
public static int TYPE_POLL = 3;
private final String question; private final String question;
private Entry[] entries; private Entry[] entries;
private int availableVoteCount; private int availableVoteCount;

3
app/src/main/java/gr/thmmy/mthmmy/model/TopicItem.java

@ -1,4 +1,5 @@
package gr.thmmy.mthmmy.model; package gr.thmmy.mthmmy.model;
public class TopicItem { public abstract class TopicItem {
} }

13
app/src/main/java/gr/thmmy/mthmmy/viewmodel/TopicViewModel.java

@ -20,6 +20,7 @@ import gr.thmmy.mthmmy.activities.topic.tasks.TopicTask;
import gr.thmmy.mthmmy.activities.topic.tasks.TopicTaskResult; import gr.thmmy.mthmmy.activities.topic.tasks.TopicTaskResult;
import gr.thmmy.mthmmy.base.BaseActivity; import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.model.Post; import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.TopicItem;
import gr.thmmy.mthmmy.session.SessionManager; import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.parsing.ParseHelpers; import gr.thmmy.mthmmy.utils.parsing.ParseHelpers;
import timber.log.Timber; import timber.log.Timber;
@ -65,7 +66,7 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
private MutableLiveData<String> replyPageUrl = new MutableLiveData<>(); private MutableLiveData<String> replyPageUrl = new MutableLiveData<>();
private MutableLiveData<Integer> pageTopicId = new MutableLiveData<>(); private MutableLiveData<Integer> pageTopicId = new MutableLiveData<>();
private MutableLiveData<String> topicTitle = new MutableLiveData<>(); private MutableLiveData<String> topicTitle = new MutableLiveData<>();
private MutableLiveData<ArrayList<Post>> postsList = new MutableLiveData<>(); private MutableLiveData<ArrayList<TopicItem>> topicItems = new MutableLiveData<>();
private MutableLiveData<Integer> focusedPostIndex = new MutableLiveData<>(); private MutableLiveData<Integer> focusedPostIndex = new MutableLiveData<>();
private MutableLiveData<TopicTask.ResultCode> topicTaskResultCode = new MutableLiveData<>(); private MutableLiveData<TopicTask.ResultCode> topicTaskResultCode = new MutableLiveData<>();
private MutableLiveData<String> topicTreeAndMods = new MutableLiveData<>(); private MutableLiveData<String> topicTreeAndMods = new MutableLiveData<>();
@ -193,7 +194,7 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
replyPageUrl.setValue(result.getReplyPageUrl()); replyPageUrl.setValue(result.getReplyPageUrl());
topicTitle.setValue(result.getTopicTitle()); topicTitle.setValue(result.getTopicTitle());
pageIndicatorIndex.setValue(result.getCurrentPageIndex()); pageIndicatorIndex.setValue(result.getCurrentPageIndex());
postsList.setValue(result.getNewPostsList()); topicItems.setValue(result.getNewPostsList());
focusedPostIndex.setValue(result.getFocusedPostIndex()); focusedPostIndex.setValue(result.getFocusedPostIndex());
isUserExtraInfoVisibile.clear(); isUserExtraInfoVisibile.clear();
for (int i = 0; i < result.getNewPostsList().size(); i++) { for (int i = 0; i < result.getNewPostsList().size(); i++) {
@ -262,8 +263,8 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
return focusedPostIndex; return focusedPostIndex;
} }
public MutableLiveData<ArrayList<Post>> getPostsList() { public MutableLiveData<ArrayList<TopicItem>> getTopicItems() {
return postsList; return topicItems;
} }
public MutableLiveData<String> getReplyPageUrl() { public MutableLiveData<String> getReplyPageUrl() {
@ -388,8 +389,8 @@ public class TopicViewModel extends BaseViewModel implements TopicTask.OnTopicTa
} }
public int postCount() { public int postCount() {
if (postsList.getValue() == null) if (topicItems.getValue() == null)
throw new NullPointerException("No page has been loaded yet!"); throw new NullPointerException("No page has been loaded yet!");
return postsList.getValue().size(); return topicItems.getValue().size();
} }
} }

Loading…
Cancel
Save