Change text in recycleview with custom font - java

I would like to change the font of my 'item' in recycleview with custom font. Anybody can help me with this? I manage to change the font for my header by using
header_title = (TextView) itemView.findViewById(R.id.header_title);
and
Typeface face_01 = Typeface.createFromAsset(itemView.getContext().getAssets(), "customfont/grb.otf");
header_title.setTypeface(face_01);
But i have no idea how to do that for item in arraylist.
Here is the java code for my adapter:-
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
TextView itemTextView = new TextView(context);
itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
itemTextView.setTextColor(0x88000000);
itemTextView.setLayoutParams(
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new RecyclerView.ViewHolder(itemTextView) {
};
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
TextView itemTextView = (TextView) holder.itemView;
itemTextView.setText(data.get(position).text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
Typeface face_01 = Typeface.createFromAsset(itemView.getContext().getAssets(), "customfont/grb.otf");
header_title.setTypeface(face_01);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}

Gloabally define fontpath and typeface
Typeface typeface;
String fontpath = "fonts/KaushanScript-Regular.otf";
In your constructor do following
public ExpandableListAdapter(Context context,List<Item> data) {
typeface = Typeface.createFromAsset(context.getAssets(), fontpath);
this.data = data;
}
In your BindViewHolder
holder.itemTextView.setTypeface(typeface);

Related

How to get data from nested Recycler View having CheckBox?

Actually this screen displays a set of questions and the task is to read the user entered or selected answer.
So the my question is, how to get the value from ChooseAdapter to QuestionAdapter and then get all the value from QuestionAdapter to my Activity.
My english is little bit weak, sorry for that.
And thanks in advance.
Main adapter : QuestionAdapter.java
public class QuestionsAdapter extends RecyclerView.Adapter<QuestionsAdapter.RecyclerViewHolder> {
private ArrayList<Question> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = QuestionsAdapter.class.getSimpleName();
private static Context mContext;
private NetworkManager nm;
private boolean visibility = false;
private ChoiceAdapter adapter;
private ArrayList<QuestionsAnswer> questionsAnswers = new ArrayList<>();
ArrayList<ChoiceAnswer> choiceAnswers;
public QuestionsAdapter(Context context, ArrayList<Question> recyclerViewItems) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Question data = (Question) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.txtQuestion.setText(data.getQuestion());
recyclerViewHolder.txtQuestionType.setText(data.getQuestionType());
if (data.getQuestionType().equals("MULT")) {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.VISIBLE);
recyclerViewHolder.edtQuestion.setVisibility(View.GONE);
if (data.getChoices().size() > 0) {
adapter = new ChoiceAdapter(mContext, data.getChoices(), position);
recyclerViewHolder.mRecyclerChoice.setAdapter(adapter);
}
} else {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.GONE);
recyclerViewHolder.edtQuestion.setVisibility(View.VISIBLE);
}
recyclerViewHolder.btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (data.getQuestionType().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + recyclerViewHolder.edtQuestion.getText().toString());
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView txtQuestion,txtQuestionType;
EditText edtQuestion;
RecyclerView mRecyclerChoice;
Button btnOk;
private LinearLayoutManager linearLayoutManager;
public RecyclerViewHolder(View view) {
super(view);
txtQuestion = view.findViewById(R.id.txt_question);
edtQuestion = view.findViewById(R.id.edt_question);
mRecyclerChoice = view.findViewById(R.id.recycler_choice);
btnOk = view.findViewById(R.id.btn_ok);
txtQuestionType = view.findViewById(R.id.txt_question_type);
initRecyclerView();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtQuestionType.getText().toString().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + edtQuestion.getText().toString());
}
}
});
}
private void initRecyclerView() {
//setting properties of recyclerView
mRecyclerChoice.setHasFixedSize(true);
mRecyclerChoice.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(mContext);
mRecyclerChoice.setLayoutManager(linearLayoutManager);
}
}
public static void validation() {
Toast.makeText(mContext, "testing", Toast.LENGTH_SHORT).show();
}}
for list of CheckBox : ChooseAdapter.java
public class ChoiceAdapter extends RecyclerView.Adapter<ChoiceAdapter.RecyclerViewHolder> {
private ArrayList<Choice> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = ChoiceAdapter.class.getSimpleName();
private Context mContext;
private NetworkManager nm;
// private OnItemClickListener mOnItemClickListener;
private boolean visibility = false;
private static ArrayList<ChoiceAnswer> choiceAnswerArrayList;
private ChoiceAnswer choiceAnswer;
String arrayData;
public ChoiceAdapter(Context context, ArrayList<Choice> recyclerViewItems, int position) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
// choiceAnswer.key = 0;
choiceAnswerArrayList = new ArrayList<>();
//initializing choiceAnswer
choiceAnswer = new ChoiceAnswer();
choiceAnswer.values = new ArrayList<>();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio_button, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Choice data = (Choice) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.checkChoice.setText(data.getChoiceName());
recyclerViewHolder.checkChoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
arrayData = "";
for (int i = 0; i < mRecyclerViewItems.size(); i++) {
if (isChecked) {
if (!choiceAnswer.values.contains(data.getChoiceID())) {
choiceAnswer.values.add(i, data.getChoiceID());
}
} else {
choiceAnswer.values.remove(data.getChoiceID());
// arrayData = choiceAnswer.values.toString().replace("[", "").replace("]", "").trim();
}
try {
arrayData = arrayData + "," + choiceAnswer.values.get(i);
}catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public String getChoiceAnswer() {
return arrayData;
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
CheckBox checkChoice;
public RecyclerViewHolder(View view) {
super(view);
checkChoice = view.findViewById(R.id.check_choice);
}
}}
Please help me guys I am trying this since last 3 days...
I've implemented my own login too, but it didn't working properly.

How can I change the colour of recyclerView item on button pressed?

I have a fragment containing a recyclerView.
When a user presses on one of their recorded exercise sets, the particular set is highlighted green.
Basically this allows them to update the weight/ reps for that particular set if they want to.
When a user then decides to press the update button, I will run a SQL query to update the weight/ reps as they entered, however I also need to deselect the selected set (recyclerView item).
I need the colour to return back to dark grey. How could this be achieved?
Fragment (Relative Code)
#Override
public void onExerciseClicked(int position) {
if (recyclerItemClicked == false) {
saveBtn.setText("Update");
clearBtn.setVisibility(View.GONE);
recyclerItemClicked = true;
double selectedWeight = adapter.getWeight(position);
String selectedWeightString = Double.toString(selectedWeight);
editTextWeight.setText(selectedWeightString);
int selectedReps = adapter.getReps(position);
String selectedRepsString = Integer.toString(selectedReps);
editTextReps.setText(selectedRepsString);
} else {
clearBtn.setVisibility(View.VISIBLE);
saveBtn.setText("Save");
recyclerItemClicked = false;
}
}
public void initRecyclerView() {
adapter = new CompletedExercisesListAdapter2(allExercises, this);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
}
Adapter
public class CompletedExercisesListAdapter2 extends RecyclerView.Adapter {
private OnExerciseClickListener onExerciseClickListener;
private List<Log_Entries> allCompletedExercises = new ArrayList<>();
public int adapterPos = -1;
public boolean isSelected = false;
public boolean swipeDetected = false;
public CompletedExercisesListAdapter2(ArrayList<Log_Entries> allCompletedExercises, OnExerciseClickListener onExerciseClickListener) {
this.allCompletedExercises = allCompletedExercises;
this.onExerciseClickListener = onExerciseClickListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == 0) {
view = layoutInflater.inflate(R.layout.new_completed_exercise_item, parent, false);
return new ViewHolderOne(view, onExerciseClickListener);
}
view = layoutInflater.inflate(R.layout.completed_exercise_item, parent, false);
return new ViewHolderTwo(view, onExerciseClickListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == 0) {
ViewHolderOne viewHolderOne = (ViewHolderOne) holder;
Log.d("adapterPos", String.valueOf(adapterPos));
Log.d("position", String.valueOf(position));
if (adapterPos == position) {
viewHolderOne.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderOne.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderOne.textViewExerciseName.setText(String.valueOf(allCompletedExercises.get(position).getChildExerciseName()));
viewHolderOne.textViewSetNumber.setText(String.valueOf(viewHolderOne.getAdapterPosition() + 1));
viewHolderOne.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderOne.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
} else if (getItemViewType(position) == 1) {
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) holder;
if (adapterPos == position) {
viewHolderTwo.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
if(adapterPos >-1 && swipeDetected == true){
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderTwo.textViewSetNumber.setText(String.valueOf(viewHolderTwo.getAdapterPosition() + 1));
viewHolderTwo.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderTwo.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
}
}
#Override
public int getItemCount() {
return allCompletedExercises.size();
}
#Override
public int getItemViewType(int position) {
// if list is sorted chronologically
if (position == 0) {
return 0;
}
if (allCompletedExercises.get(position).getChildExerciseName().equals(allCompletedExercises.get(position - 1).getChildExerciseName())) {
return 1;
} else {
return 0;
}
}
public class ViewHolderOne extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewExerciseName;
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderOne(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewExerciseName = itemView.findViewById(R.id.textView_ExerciseName3);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number56);
textViewWeight = itemView.findViewById(R.id.textView_weight78);
textViewReps = itemView.findViewById(R.id.textView_repss0);
mOnExerciseClickListener = onExerciseClickListener;
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_relative);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (isSelected) {
adapterPos = -1;
isSelected = false;
} else {
adapterPos = getAdapterPosition();
isSelected = true;
}
notifyDataSetChanged();
}
}
class ViewHolderTwo extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderTwo(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number);
textViewWeight = itemView.findViewById(R.id.textView_weight);
textViewReps = itemView.findViewById(R.id.textView_repss);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_rel);
mOnExerciseClickListener = onExerciseClickListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (!isSelected) {
adapterPos = getAdapterPosition();
isSelected = true;
} else {
adapterPos = -1;
isSelected = false;
}
notifyDataSetChanged();
}
}
public interface OnExerciseClickListener {
void onExerciseClicked(int position);
}
}
}
Create a separate method in your adapter for clearing the selection.
public void clearSelection() {
adapterPos = -1;
isSelected = false;
notifyDataSetChanged();
}
Then call adapter.clearSelection() from your update click listener.

How to take the value of the checked row in list view, and get the prefered text field?

I fulfill the AlertDIalog and ListView with two values Name and id, and I cannot find conclusion оr the right way, when i checked some CheckBoxes, i need the value of the Checked/Selected rows of (id's text) to save.
#OnClick(R.id.group_delete)
void deleteGroup() {
AlertDialog.Builder dialog4 = new AlertDialog.Builder(PreviewActivity.this);
LayoutInflater inflater2 = getLayoutInflater();
View convertView2 = (View) inflater2.inflate(R.layout.alert_dialog_delete_group, null);
dialog4.setView(convertView2);
ListView listView2 = (ListView) convertView2.findViewById(R.id.listViewGroup);
final List<Item> groupList = this.getGroup();
CustomAdapter listAdapter2 = new CustomAdapter(getBaseContext(), groupList);
// listAdapter2.notifyDataSetChanged();
convertView2.setTag(dialog4);
// SparseBooleanArray sp = listView2.getCheckedItemPositions();
listView2.setOnItemClickListener((AdapterView<?> adapterView, View view, int position, long l) -> {
// Get user selected item.
Object itemObject = adapterView.getAdapter();
Item itemDto = (Item) itemObject;
CheckBox itemCheckbox = (CheckBox) convertView2.findViewById(R.id.checkMark5);
listAdapter2.setCheckedItem(position);
});
ImageView delete = (ImageView) convertView2.findViewById(R.id.del_group);
delete.setOnClickListener((View view) -> {
CheckBox itemCheckbox = (CheckBox) convertView2.findViewById(R.id.checkMark5);
Iterator<String> it = listAdapter2.getCheckedItems().values().iterator();
for (int i=0;i<listAdapter2.getCheckedItems().size();i++){
//Do whatever
// String result = "";
// ArrayList<String> resultList = new ArrayList<String>();
// for (int y = 0; y < resultList.size(); y++) {
// result += String.valueOf(resultList.get(i)) + "\n";
// }
// if (result.matches("")) {
////
// Toast.makeText(getApplicationContext(),"Please select some thing from list to show",Toast.LENGTH_LONG).show();
// }
// else {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// }
listAdapter2.getItem(Integer.parseInt(it.next()));
}
// List<Item> resultList = listAdapter2.getCheckedItems();
// for (int i = 0; i < resultList.size(); i++) {
// result += String.valueOf(resultList.get(i)) + "\n";
// }
// listAdapter2.getCheckedItemPositions().toString();
//
// if (result.matches("")) {
//
// Toast.makeText(getApplicationContext(),"Please select some thing from list to show",Toast.LENGTH_LONG).show();
// }
// else {
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
// }
// shared.setSharedPreferencesString(Constants.ID, size2);
listAdapter2.notifyDataSetChanged();
});
listView2.setAdapter(listAdapter2);
listView2.setTag(dialog4);
AlertDialog alert4 = dialog4.create();
alert4.show();
alert4.getWindow().
setBackgroundDrawable(new ColorDrawable(android.graphics.Color.argb(0, 100, 100, 100)));
}
public List<Company> getCompanies() {
return mCompanies;
}
private List<Item> getGroup() {
ArrayList<String> groups = new ArrayList<String>();
ArrayList<String> groups2 = new ArrayList<>();
for (Group group2 : mRepository.getCompanies().get(posit).getGroups()) {
groups2.add(group2.getId());
}
for (Group group1 : mRepository.getCompanies().get(posit).getGroups()) {
groups.add(group1.getName());
}
List<Item> ret = new ArrayList<Item>();
int length = groups.size();
for (int i = 0; i < length; i++) {
String itemText2 = groups.get(i);
String itemText3 = groups2.get(i);
Item dto = new Item();
dto.setChecked(false);
dto.setIdText(itemText3);
dto.setItemText(itemText2);
ret.add(dto);
}
return ret;
}
Item Class:
public class Item {
private boolean checked ;
private String itemText = "";
private String IdText = "";
private String IdText2 = "";
public String getIdText2() {
return IdText2;
}
public void setIdText2(String idText2) {
IdText2 = idText2;
}
public String getIdText() {
return IdText;
}
public void setIdText(String idText) {
IdText = idText;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getItemText() {
return itemText;
}
public void setItemText(String itemText) {
this.itemText = itemText;
}}
CustomAdapter :
public class CustomAdapter extends BaseAdapter {
private List<Item> ItemList ;
public HashMap<String, String> checked = new HashMap<String, String>();
private Context ctx;
public CustomAdapter(Context ctx, List<Item> ItemList) {
this.ctx = ctx;
this.ItemList = ItemList;
}
public void setCheckedItem(int item) {
if (checked.containsKey(String.valueOf(item))) {
checked.remove(String.valueOf(item));
} else {
checked.put(String.valueOf(item), String.valueOf(item));
}
}
public HashMap<String, String> getCheckedItems() {
return checked;
}
#Override
public int getCount() {
return ItemList.size();
}
#Override
public Object getItem(int position) {
return ItemList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ItemViewHolder viewHolder = null;
if (convertView != null) {
viewHolder = (ItemViewHolder) convertView.getTag();
} else {
convertView = View.inflate(ctx, R.layout.custom, null);
CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkMark5);
TextView listItemText = (TextView) convertView.findViewById(R.id.item_unit_id5);
TextView tetx = (TextView) convertView.findViewById(R.id.tekst5);
TextView textId = (TextView) convertView.findViewById(R.id.item_number5);
viewHolder = new ItemViewHolder(convertView);
viewHolder.setItemCheckbox(checkbox);
viewHolder.setItemTextView(listItemText);
viewHolder.setIdTextView(textId);
viewHolder.setIdTextView2(tetx);
convertView.setTag(viewHolder);
}
Item items = ItemList.get(position);
viewHolder.getItemCheckbox().setChecked(items.isChecked());
viewHolder.getItemTextView().setText(items.getItemText());
viewHolder.getIdTextView().setText(items.getIdText());
viewHolder.getIdTextView2().setText(items.getIdText2());
return convertView;
}}
ViewHolder :
public class ItemViewHolder extends RecyclerView.ViewHolder {
private CheckBox itemCheckbox;
private TextView IdTextView;
private TextView itemTextView;
private TextView IdTextView2;
public TextView getIdTextView2() {
return IdTextView2;
}
public void setIdTextView2(TextView idTextView2) {
IdTextView2 = idTextView2;
}
public ItemViewHolder(View itemView) {
super(itemView);
}
public TextView getIdTextView() {
return IdTextView;
}
public void setIdTextView(TextView idTextView) {
IdTextView = idTextView;
}
public CheckBox getItemCheckbox() {
return itemCheckbox;
}
public void setItemCheckbox(CheckBox itemCheckbox) {
this.itemCheckbox = itemCheckbox;
}
public TextView getItemTextView() {
return itemTextView;
}
public void setItemTextView(TextView itemTextView) {
this.itemTextView = itemTextView;
} }

How to show the contents of a list?

In my application I get some data from server and show this into my recyclerView.
I want show all of list content not show just item 0.
My adapter codes:
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> {
private ArrayList<Post> postList;
private Context context;
private ListItemClickListener itemClickListener;
public PostsAdapter(Context context, ArrayList<Post> allPostList) {
this.context = context;
postList = allPostList;
}
public void setItemClickListener(ListItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false);
return new ViewHolder(view, viewType, itemClickListener);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imgPost;
private TextView tvPostTitle, tvPostCategory, tvPostDate;
private CardView mCardView;
private ListItemClickListener itemClickListener;
public ViewHolder(View itemView, int viewType, ListItemClickListener itemClickListener) {
super(itemView);
this.itemClickListener = itemClickListener;
// Find all views ids
imgPost = (ImageView) itemView.findViewById(R.id.post_img);
tvPostTitle = (TextView) itemView.findViewById(R.id.title_text);
tvPostCategory = (TextView) itemView.findViewById(R.id.post_category);
tvPostDate = (TextView) itemView.findViewById(R.id.date_text);
mCardView = (CardView) itemView.findViewById(R.id.card_view_top);
mCardView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (itemClickListener != null) {
itemClickListener.onItemClick(getLayoutPosition(), view);
}
}
}
#Override
public int getItemCount() {
return (null != postList ? postList.size() : 0);
}
#Override
public void onBindViewHolder(PostsAdapter.ViewHolder mainHolder, int position) {
final Post model = postList.get(position);
// setting data over views
String title = model.getTitle().getRendered();
mainHolder.tvPostTitle.setText(Html.fromHtml(title));
String imgUrl = null;
if (model.getEmbedded().getWpFeaturedMedias().size() > 0) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails() != null) {
if (model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl() != null) {
imgUrl = model.getEmbedded().getWpFeaturedMedias().get(0).getMediaDetails().getSizes().getFullSize().getSourceUrl();
}
}
}
if (imgUrl != null) {
Glide.with(context)
.load(imgUrl)
.into(mainHolder.imgPost);
} else {
Glide.with(context)
.load(R.color.imgPlaceholder)
.into(mainHolder.imgPost);
}
String category = null;
if (model.getEmbedded().getWpTerms().size() >= 1) {
category = model.getEmbedded().getWpTerms().get(0).get(0).getName();
}
if (category == null) {
category = context.getResources().getString(R.string.default_str);
}
mainHolder.tvPostCategory.setText(Html.fromHtml(category));
mainHolder.tvPostDate.setText(model.getFormattedDate());
}
}
but in above code just show me item 0 , but I want show all of items.
how can I it?
Try this
for (int i = 0; i < model.getEmbedded().getWpTerms().size(); i++) {
for (int j=0;j<model.getEmbedded().getWpTerms().get(i).size();j++){
Log.e("DATA",model.getEmbedded().getWpTerms().get(i).get(j).getName());
}
}
String category = "";
for(int i=0; response.size();i++){
{
category = category + "," + model.getEmbedded().getWpTerms().get(i).get(i).getName();
}
If you have used recyclerview , its adapter has onBindViewHolder() method , which gives you a position variable. Use that to iterate through the list!
model.getEmbedded().getWpFeaturedMedias().get(position).getMediaDetails()

Recyclerview change item position automatically when scrolling

In my application i have custom adapter, adapter has image, and text when I scrolling the RecyclerView some items position automatic change
public class MyPhotosAdapter extends RecyclerView.Adapter<MyPhotosAdapter.ViewHolder> implements View.OnClickListener {
private PojoClasses.DashboardPhotos[] dashboardPhotoses;
private static final int TWEET_COMPOSER_REQUEST_CODE = 500;
Activity mActivity;
private ProgressDialog pDialog;
private static final String IMAGE_DIRECTORY_NAME = "My City Tag";
static File mediaFile;
static File mediaStorageDir;
static String mediaName = null;
static Integer twCurrent, fbCurrent;
ShareDialog shareDialog;
CallbackManager callbackManager;
private static final String CURRENT_USER_VIOLATION_ID = "twuserVId";
private static final String PREF_KEY_FACEBOOK_LOGIN = "facebook_loggedin";
private static final String PREF_KEY_TWITTER_LOGIN = "twitter_loggedin";
private static final String PREF_NAME = "my city tag";
private static SharedPreferences mSharedPreferences;
boolean isLoggedInTW;
boolean isLoggedInFB;
int isShareFb = 0;
DBHelper dbHelper;
public MyPhotosAdapter(PojoClasses.DashboardPhotos[] dashboardPhotoses) {
this.dashboardPhotoses = dashboardPhotoses;
}
public MyPhotosAdapter(Activity activity, PojoClasses.DashboardPhotos[] dashboardPhotoses) {
this.dashboardPhotoses = dashboardPhotoses;
mActivity = activity;
}
// Create new views (invoked by the layout manager)
#Override
public MyPhotosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
FacebookSdk.sdkInitialize(mActivity);
callbackManager = CallbackManager.Factory.create();
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY,TWITTER_SECRET);
Fabric.with(mActivity, new com.twitter.sdk.android.Twitter(authConfig));
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_photo, null);
dbHelper = new DBHelper(mActivity);
Fabric.with(mActivity, new TweetComposer());
shareDialog=new ShareDialog(mActivity);
/* Initialize application preferences */
mSharedPreferences = mActivity.getSharedPreferences(PREF_NAME, 0);
isLoggedInFB = mSharedPreferences.getBoolean(PREF_KEY_FACEBOOK_LOGIN, false);
isLoggedInTW = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.mImageViewCapUser.setImageBitmap(dashboardPhotoses[position].getThumbnail());
viewHolder.txtDescription.setText(dashboardPhotoses[position].getDescription());
viewHolder.txtDate.setText(dashboardPhotoses[position].getCreatedDate());
viewHolder.txtViolation.setText(dashboardPhotoses[position].getViolation());
final int FB = dashboardPhotoses[position].getIsShareFb();
final int TW = dashboardPhotoses[position].getIsShareTw();
final int priority = dashboardPhotoses[position].getPriority();
switch (priority) {
case 2:
viewHolder.mImageViewPriority.setBackgroundColor(Color.parseColor("#D50000"));
break;
case 3:
viewHolder.mImageViewPriority.setBackgroundColor(Color.parseColor("#FF9800"));
break;
case 4:
viewHolder.mImageViewPriority.setBackgroundColor(Color.parseColor("#FFEB3B"));
break;
}
viewHolder.mImageViewIcon.setTag(dashboardPhotoses[position]);
if (FB == 0) {
viewHolder.mImageViewIcon.setImageResource(R.drawable.ic_action_share);
viewHolder.mImageViewIcon.setFocusable(false);
viewHolder.mImageViewIcon.setFocusableInTouchMode(false);
viewHolder.mImageViewIcon.setClickable(true);
viewHolder.mImageViewIcon.setOnClickListener(this);
} else if (TW == 0) {
viewHolder.mImageViewIcon.setImageResource(R.drawable.ic_action_share);
viewHolder.mImageViewIcon.setFocusable(false);
viewHolder.mImageViewIcon.setFocusableInTouchMode(false);
viewHolder.mImageViewIcon.setClickable(true);
viewHolder.mImageViewIcon.setOnClickListener(this);
} else {
viewHolder.mImageViewIcon.setImageResource(R.mipmap.ic_send);
}
viewHolder.txtDescription.setTag(dashboardPhotoses[position]);
if (FB == 0) {
viewHolder.txtDescription.setFocusable(false);
viewHolder.txtDescription.setFocusableInTouchMode(false);
viewHolder.txtDescription.setClickable(true);
viewHolder.txtDescription.setOnClickListener(this);
} else if (TW == 0) {
viewHolder.txtDescription.setFocusable(false);
viewHolder.txtDescription.setFocusableInTouchMode(false);
viewHolder.txtDescription.setClickable(true);
viewHolder.txtDescription.setOnClickListener(this);
} else {
}
}
#Override
public void onClick(View v) {
PojoClasses.DashboardPhotos dashboardPhotos;
switch (v.getId()){
case R.id.imgv_Icon_list:
dashboardPhotos = (PojoClasses.DashboardPhotos) v.getTag();
int fb = dashboardPhotos.getIsShareFb();
int tw = dashboardPhotos.getIsShareTw();
if(fb == 0 && tw == 0) {
selectSocial(dashboardPhotos);
}
else if(fb == 0){
selectSocialfb(dashboardPhotos);
}
else if(tw == 0){
selectSocialtw(dashboardPhotos);
}
break;
case R.id.txt_tag_des:
dashboardPhotos = (PojoClasses.DashboardPhotos) v.getTag();
Intent i = new Intent(mActivity,EditViolationActivity.class);
i.putExtra("UserViolationId",dashboardPhotos.getUserViolationId());
mActivity.startActivity(i);
break;
}
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public static TextView txtDescription;
public ImageView mImageViewCapUser;
public TextView txtDate;
public TextView txtViolation;
public static ImageView mImageViewIcon;
public View mImageViewPriority;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtDescription = (TextView) itemLayoutView.findViewById(R.id.txt_tag_des);
txtDate = (TextView) itemLayoutView.findViewById(R.id.txt_date);
txtViolation = (TextView) itemLayoutView.findViewById(R.id.txt_violation);
mImageViewCapUser = (ImageView) itemLayoutView.findViewById(R.id.imgv_capture_user);
mImageViewIcon = (ImageView) itemLayoutView.findViewById(R.id.imgv_Icon_list);
mImageViewPriority = itemLayoutView.findViewById(R.id.imgv_priority);
}
}
#Override
public int getItemCount() {
return dashboardPhotoses.length;
}
}
Please help me if anyone have solution for that particular problem .
Thanks in advance
Put a default in your switch statement
default:
viewHolder.mImageViewPriority.setBackgroundColor("Default color here for other priorities");
break;
and put default values in else part of all your if else conditions

Categories

Resources