PLEASE READ THE EDIT SECTION BELLOW
I have a Spinners Recyclerview (list) I want to iterate after clicking a button(finishBtn).
in order to get the selected results entered by the user, I try to iterate the list using list.findViewHolderForAdapterPosition.
The size of the list is supposed to be 6 (by viewing Recyclerview I can see all 6) but when I try to iterate, the size is smaller than what actually there is. (instead of 6 the list.getChildCount() is only 3).
Fragment:
public class FragmentUserDetails extends Fragment {
Button finishBtn;
LinkedHashMap<String, ArrayList<String>> detailsQuestions;
DetailsViewModel detailsViewModel;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
detailsViewModel = new ViewModelProvider(this).get(DetailsViewModel.class);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_details, container, false);
detailsQuestions =getQuestions();
Log.d("TAG", "size: "+detailsQuestions.size());
RecyclerView list = view.findViewById(R.id.details_list_rv);
list.setHasFixedSize(true);
list.setLayoutManager(new LinearLayoutManager(getContext()));
DetailsAdapter detailsAdapter = new DetailsAdapter(this);
list.setAdapter(detailsAdapter);
finishBtn = view.findViewById(R.id.userDetails_next_btn);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
finishBtn.setOnClickListener(v -> {
Log.d("TAG", ""+list.getChildCount());
for (int i = 0; i < list.getChildCount(); i++) {
DetailsHolder holder = (DetailsHolder) list.findViewHolderForAdapterPosition(i);
if (holder!=null) {
String question = (String) detailsQuestions.keySet().toArray()[i];
Log.d("TAG", "The answer for " +question+"is :"+ holder.questionSp.getSelectedItem().toString());
}
}
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
getActivity().finish();
});
return view;
}
interface OnItemClickListener {
void onItemClick(int position);
}
public LinkedHashMap<String, ArrayList<String>> getQuestions() {
ArrayList<Detail> arrayList = detailsViewModel.getDetails();
detailsQuestions = new LinkedHashMap<>();
for (Detail detail : arrayList) {
detailsQuestions.put(detail.getQuestion(), detail.getAnswers());
}
return detailsQuestions;
}
}
Adapter:
class DetailsAdapter extends RecyclerView.Adapter<DetailsHolder> {
private final FragmentUserDetails fragmentUserDetails;
FragmentUserDetails.OnItemClickListener listener;
public DetailsAdapter(FragmentUserDetails fragmentUserDetails) {
this.fragmentUserDetails = fragmentUserDetails;
}
public void setOnItemClickListener(FragmentUserDetails.OnItemClickListener listener) {
this.listener = listener;
}
#NonNull
#Override
public DetailsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = fragmentUserDetails.getLayoutInflater().inflate(R.layout.details_list_row, parent, false);
DetailsHolder detailsHolder = new DetailsHolder(view, listener);
return detailsHolder;
}
#Override
public void onBindViewHolder(#NonNull DetailsHolder detailsHolder, int position) {
if(fragmentUserDetails.detailsQuestions.size()!=0) {
String detail = (String) fragmentUserDetails.detailsQuestions.keySet().toArray()[position];
fragmentUserDetails.detailsQuestions.get(detail).add(0,detail);
String[] array = fragmentUserDetails.detailsQuestions.get(detail).toArray(new String[0]);
ArrayAdapter adapter = new ArrayAdapter<String>(fragmentUserDetails.getContext(), R.layout.spinner_item, array){
#Override
public boolean isEnabled(int position) {
if (position == 0) {
return false;
} else {
return true;
}
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if (position == 0) {
// Set the hint text color gray
tv.setTextColor(Color.GRAY);
} else {
tv.setTextColor(Color.WHITE);
}
return view;
}};
detailsHolder.questionSp.setAdapter(adapter);
adapter.setDropDownViewResource(R.layout.spinner_item);
}
}
#Override
public int getItemCount() {
return fragmentUserDetails.detailsQuestions.size();
}
}
Holder:
class DetailsHolder extends RecyclerView.ViewHolder {
Spinner questionSp;
public DetailsHolder(#NonNull View itemView, FragmentUserDetails.OnItemClickListener listener) {
super(itemView);
questionSp = itemView.findViewById(R.id.listrow_question_sp);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
listener.onItemClick(pos);
}
});
}
}
details_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true">
<Spinner
android:id="#+id/listrow_question_sp"
android:layout_width="409dp"
android:layout_height="90dp"
android:layout_weight="1"
android:clickable="true"
android:drawablePadding="14dp"
android:focusable="true"
android:maxLines="1"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:spinnerMode="dialog"
android:textSize="18sp"
android:theme="#style/mySpinnerItemStyle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_user_details.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".details.FragmentUserDetails">
<ImageView
android:id="#+id/userDetails_img_main"
android:layout_width="306dp"
android:layout_height="160dp"
android:layout_marginTop="30dp"
android:src="#drawable/logo__nobg_2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/homeScr_text_title"
android:layout_width="350dp"
android:layout_height="90dp"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-light"
android:gravity="center"
android:text="Please enter the following details:"
android:textColor="#color/white"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/userDetails_img_main" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/details_list_rv"
android:layout_width="402dp"
android:layout_height="211dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/homeScr_text_title" />
<com.google.android.material.button.MaterialButton
android:id="#+id/userDetails_next_btn"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginTop="3dp"
android:fontFamily="sans-serif-black"
android:text="NEXT"
android:textSize="20sp"
app:cornerRadius="35dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_ti" />
<com.google.android.material.button.MaterialButton
android:id="#+id/userDetails_btn_back"
style="#style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="88dp"
android:layout_height="50dp"
android:layout_marginTop="3dp"
android:backgroundTint="#color/black"
android:fontFamily="sans-serif"
android:text="BACK"
android:textSize="20sp"
app:cornerRadius="35dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details_ti"
app:strokeColor="#color/primeOrng"
app:strokeWidth="1dp" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/details_ti"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif-light"
android:hint="map.."
android:textColorHint="#color/white"
app:layout_constraintTop_toBottomOf="#+id/details_list_rv"
tools:layout_editor_absoluteX="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/listrow_question_et"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_input"
android:drawablePadding="14dp"
android:fontFamily="sans-serif-light"
android:inputType="text"
android:maxLines="1"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:textColor="#color/white"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="#+id/details_ti"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
tools:layout_editor_absoluteX="0dp" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
How can I solve this?
EDIT:
By replacing :
list.getChildCount();
with:
list.getAdapter().getItemCount()
I get the exact size (6) and now I understand it is related to the fact RecycleView recycles the views and not keeping them all, so it will always be a maximum of 3 items(in my example).
now, my question is still how could I achieve my target of saving the selected answers in the spinners by clicking finishBtn(I understand that iterating them is not an option because of the same thing, or maybe there is a way?)
Related
Hello I am developing an app which uses recyclerview to show items to select categories. I have added textview and checkbox on recyclerview item. The problem is if I select one checkbox, it also selects multiple checkbox in the list. For example if I select 1st checkbox in the list it automatically selects every 10th checkbox in the list. Thanks
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="5dp"
android:background="#FFF"
app:cardUseCompatPadding="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/categoryName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="14dp"
android:text="Category"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="#+id/categoryCount"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/categoryCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginBottom="16dp"
android:text="Count"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<CheckBox
android:id="#+id/categoryCheck"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_marginTop="36dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="36dp"
android:buttonTint="#color/red"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
Adapter.java
public class CategorySelector extends RecyclerView.Adapter<CategorySelector.ViewHolder> {
LayoutInflater inflater;
List<Category> categoryList;
List<String> selectedItems = new ArrayList<>();
public CategorySelector(Context ctx, List<Category> categoryList){
inflater = LayoutInflater.from(ctx);
this.categoryList = categoryList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.category_select, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.categoryName.setText(categoryList.get(position).getCategoryName());
holder.categoryCount.setText(String.valueOf(categoryList.get(position).getCategoryCount()));
holder.categoryCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
selectedItems.add(categoryList.get(position).getCategoryName());
} else{
selectedItems.remove(categoryList.get(position).getCategoryName());
}
}
});
}
#Override
public int getItemCount() {
return categoryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView categoryName;
TextView categoryCount;
CheckBox categoryCheck;
public ViewHolder(#NonNull View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.categoryName);
categoryCount = itemView.findViewById(R.id.categoryCount);
categoryCheck = itemView.findViewById(R.id.categoryCheck);
}
}
public List<String> getSelectedItems(){
return selectedItems;
}
}
In your checkBox changeListener use instead of using position use :
holder.getAdapterPosition()
then set your checkBox select with your item :
holder.categoryCheck.setChecked(//set your boolean is selected before);
I ran into a problem and still don't know how to get out. I made a listview with a custom adapter for it. I also implemented a searchview which will update the listview everytime I type in a character. But the problem is that the listview is not showing the correct results. I put some checkpoints in getView method of the custom adapter to check if the values which will be displayed are right or not and they're all right.
I have two items, let's call them HD03 and HD02 as you can see their name on the top left corner of each item.
when I type in the search bar 02, the result must be item HD02 but I got item HD03 instead. Although, the value I checked in the getView method using debugger was HD02
I think I made a silly mistake somewhere but I can't find it. Thank you for your time !
Here're my fragment and my adapter code.
Fragment
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
private ListView listViewContract;
private SearchView contractSearchView;
private ContractAdapter productListAdapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
initView(root);
return root;
}
private void initView(View view) {
listViewContract = view.findViewById(R.id.contract_list);
listViewContract.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listViewProduct_onItemClick(adapterView, view, i, l);
}
});
loadData();
contractSearchView = view.findViewById(R.id.search_bar);
contractSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
DashboardFragment.this.productListAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
DashboardFragment.this.productListAdapter.getFilter().filter(newText);
return false;
}
});
}
private void loadData() {
List<Contract> products = new ArrayList<Contract>();
products.add(new Contract("p03", "Name 1", "4", "Mới", "HD03" ));
products.add(new Contract("p02", "Name 2", "5", "Mới", "HD02"));
productListAdapter = new ContractAdapter(getContext(), products);
listViewContract.setAdapter(productListAdapter);
}
private void listViewProduct_onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Product product = (Product) adapterView.getItemAtPosition(i);
// Toast.makeText(getApplicationContext(), product.getName(), Toast.LENGTH_LONG).show();
}
}
Adapter
public class ContractAdapter extends BaseAdapter implements Filterable {
private Context context;
private List<Contract> products;
private List<Contract> filteredData;
private ItemFilter itemFilter = new ItemFilter();
public ContractAdapter(Context context, List<Contract> products){
this.context = context;
this.products = products;
this.filteredData = products;
}
#NonNull
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder viewHolder;
if (view == null) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.phan_anh_cardview, parent, false);
viewHolder.textViewContractName = view.findViewById(R.id.ten_hd);
viewHolder.textViewCustomerName = view.findViewById(R.id.ten_dt);
viewHolder.textViewEmployeeName = view.findViewById(R.id.ten_nv);
viewHolder.textViewId = view.findViewById(R.id.ma_hd);
viewHolder.buttonStatus = view.findViewById(R.id.report_status);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
Contract product = filteredData.get(position);
viewHolder.textViewContractName.setText(product.getName());
viewHolder.textViewEmployeeName.setText(product.getNhanvien());
viewHolder.textViewCustomerName.setText(product.getCustomer());
viewHolder.textViewId.setText(product.get_id());
viewHolder.buttonStatus.setText(product.getStatus());
Log.i("view", viewHolder.textViewId.getText().toString());
return view;
}
public int getCount(){
return filteredData.size();
}
public Contract getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public Filter getFilter() {
return itemFilter;
// return super.getFilter();
}
private static class ViewHolder {
public static TextView textViewContractName;
public static TextView textViewCustomerName;
public static TextView textViewEmployeeName;
public static TextView textViewId;
public static Button buttonStatus;
}
private class ItemFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String query = constraint.toString();
FilterResults results = new FilterResults();
List<Contract> originalData = products;
int count = originalData.size();
List<Contract> nList = new ArrayList<>();
for (Contract contract : originalData) {
if(contract.get_id().contains(query) || contract.getName().contains(query) || contract.getCustomer().contains(query)){
nList.add(contract);
}
}
results.values = nList;
results.count = nList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (List<Contract>) results.values;
notifyDataSetChanged();
}
}
}
fragment_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.dashboard.DashboardFragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/tag_spinner_constraint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<SearchView
android:id="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="45dp"
android:iconifiedByDefault="false"
app:layout_constraintEnd_toEndOf="#id/tag_spinner_constraint"
app:layout_constraintStart_toStartOf="#id/tag_spinner_constraint"
app:layout_constraintTop_toTopOf="#id/tag_spinner_constraint" />
<HorizontalScrollView
android:id="#+id/filter_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/search_bar">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/empty_rooms_btn"
android:layout_width="99dp"
android:layout_height="34dp"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Phòng trống"
android:textSize="12sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/floor_spinner" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/not_full_rooms_btn"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Phòng ghép"
android:textSize="12sp"
app:layout_constraintStart_toEndOf="#+id/empty_rooms_btn"
app:layout_constraintTop_toBottomOf="#+id/floor_spinner" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/full_rooms_btn"
android:layout_width="105dp"
android:layout_height="34dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Phòng đã đầy"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/not_full_rooms_btn"
app:layout_constraintTop_toBottomOf="#+id/floor_spinner" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/all_rooms_btn"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:background="#drawable/rounded_button"
android:text="Tất cả"
android:textSize="12sp" />
</LinearLayout>
</HorizontalScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
<ListView
android:id="#+id/contract_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tag_spinner_constraint">
</ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
phan_anh_cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="162dp"
android:layout_marginTop="5dp"
android:padding="6dp">
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/report_status"
android:layout_width="68dp"
android:layout_height="15dp"
android:background="#drawable/rounded_button"
android:text="Mới"
android:textSize="10sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ma_hd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ten_hd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ma_hd" />
<TextView
android:id="#+id/ten_dt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ten_hd" />
<TextView
android:id="#+id/ten_nv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ten_dt" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
rounded_button.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#color/cardview_dark_background" />
<corners android:bottomRightRadius="30dp"
android:bottomLeftRadius="30dp"
android:topRightRadius="30dp"
android:topLeftRadius="30dp"/>
</shape>
I found error in your code.
You shouldn't use static members in ViewHolder.
So please replace ViewHolder code as following.
ContractAdapter.java
..............
private static class ViewHolder {
public TextView textViewContractName;
public TextView textViewCustomerName;
public TextView textViewEmployeeName;
public TextView textViewId;
public Button buttonStatus;
}
...............
If so, it will be working.
I want to display a name from my database with a delete button on the right. I have created a custom adapter with BaseAdapter. The ListView show me the right name but no ImageButton. Hope ypu can help me.
Here my Code:
Layout for each ListItem:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/PlayerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/PlayerDeleteImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="#android:color/white"
android:padding="20dp"
app:srcCompat="#drawable/ic_baseline_delete_24"
android:tint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout for my PlayerActivity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Baum.PlayerActivity">
<EditText
android:id="#+id/PayerEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:hint="#string/AddPlayerHint"
app:layout_constraintEnd_toStartOf="#+id/PlayerFloatingActionButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/PlayerListView"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottom_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/PayerEditText" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:itemBackground="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/menu_navigation" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/PlayerFloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:clickable="true"
android:onClick="onClickFloatingActionButton"
android:tint="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24"
tools:ignore="VectorDrawableCompat" />
</androidx.constraintlayout.widget.ConstraintLayout>
My Activity:
public class PlayerActivity extends Activity {
private ArrayList<String> players = new ArrayList<>();
DBHelper db = new DBHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
//Initalize custom Players
loadPlayersInArrayList();
// Show all Players in the ListView
ListView listView = (ListView) findViewById(R.id.PlayerListView);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, players);
listView.setAdapter(arrayAdapter);
//All BottomNav stuff
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.player_menu);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.player_menu:
return true;
case R.id.home_menu:
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.deck_menu:
startActivity(new Intent(getApplicationContext(), DecksActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
}
public void onClickFloatingActionButton(View v){
EditText newPlayerName = findViewById(R.id.PayerEditText);
ArrayList<Player> dbPlayers = db.getAllPlayer();
boolean newPlayer = true;
for(Player p : dbPlayers){
if(newPlayerName.getText().toString().equals(p.getName())){
newPlayer = false;
new AlertDialog.Builder(this)
.setTitle("Information")
.setMessage("Dieser Name ist bereits vergeben")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
break;
}
}
if (newPlayer){
db.addPlayer(newPlayerName.getText().toString());
loadPlayersInArrayList();
}
}
public void loadPlayersInArrayList(){
if (players != null){
players.clear();
}
ArrayList<Player> dbPlayers = db.getAllPlayer();
for(Player p : dbPlayers){
players.add(p.getName());
}
}
}
Here is my Adapter:
public class PlayerAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> items;
public PlayerAdapter(Context context, ArrayList<String> items){
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.player_list_item, parent, false);
}
String currentItem = (String) getItem(position);
TextView deckName = (TextView) convertView.findViewById(R.id.PlayerTextView);
ImageButton playerDeleteButton = (ImageButton) convertView.findViewById(R.id.PlayerDeleteImageButton);
deckName.setText(currentItem);
return convertView;
}
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
Here a screenshot of my ListView in the app:
ListView in the app
Here a screenshot from the Layout for each Item:
Screenshot Layout
I guess android.R.layout.simple_list_item_1 expect only a simple text view in the layout file. (I might be wrong as well).
Still using Base Adapter and android.R.layout.simple_list_item_1 are expected to be in a simple spinner item. For any custom layout for list item use ArrayAdapter<type>. Code as follows-
PlayerAdapter.java
public class PlayerAdapter extends ArrayAdapter<String> {
List<String> playerNameList;
public PlayerAdapter(#NonNull Context context, #NonNull List<String> playerNameList) {
//#param context, layout of list item, textview id of list item and List<String>
super(context, R.layout.player_list_item, R.id.PlayerTextView,playerNameList);
this.playerNameList = playerNameList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView playerTextView = view.findViewById(R.id.PlayerTextView);
ImageView playerDeleteImageButton = view.findViewById(R.id.PlayerDeleteImageButton);
playerTextView.setText(playerNameList.get(position));
playerDeleteImageButton.setOnClickListener(v -> {
// apply on image click code here
});
return view;
}
}
I modified to list item as well to be a simple LinearLayout -
ListItem Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dp"
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/PlayerTextView"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="20sp"
android:textStyle="bold"/>
<ImageView
android:id="#+id/PlayerDeleteImageButton"
android:src="#mipmap/ic_launcher_round"
android:layout_width="30dp"
android:layout_height="30dp"/>
</LinearLayout>
Setting PlayerAdpater
List<String> playerNameList = new ArrayList<>();
PlayerAdapter playerAdapter = new PlayerAdapter(this,playerNameList);
playerNameList.setAdapter(playerAdapter);
Hope this will help.
Happy Coding !
Probably I am missing something here, but I am animating a recyclerview to outside of its container and when it is in the final position, the click events are not triggered, neither the scroll works...
I am using the ObjectAnimator to translate it, so I thought the clickable areas were also translated. Here is the relevant code:
The Fragment
public class SlideListFragment extends Fragment {
private Button slideButton;
private RecyclerView listToSlide;
private DummyListAdapter listAdapter;
private LinearLayout listContainer;
public static SlideListFragment newInstance() {
return new SlideListFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.slide_list_fragment, container, false);
slideButton = root.findViewById(R.id.slide_up_btn);
slideButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
slideUpRoomsList();
}
});
listToSlide = root.findViewById(R.id.list_to_slide);
listContainer = root.findViewById(R.id.list_container);
setupList();
return root;
}
private void setupList() {
GridLayoutManager layoutManager = new GridLayoutManager(this.getContext(), 1);
layoutManager.setReverseLayout(true);
listToSlide.setLayoutManager(layoutManager);
listAdapter = new DummyListAdapter(this.getContext());
listToSlide.setAdapter(listAdapter);
setListData(5);
}
private void setListData(int i) {
ArrayList<DummyModel> items = new ArrayList<>();
for (int j = 0; j < i; j++) {
items.add(new DummyModel(j, "TEXT" + j));
}
listAdapter.refreshItems(items);
}
private void slideUpRoomsList() {
float height = listContainer.getHeight();
ObjectAnimator showAnimation = ObjectAnimator.ofFloat(listContainer, "translationY", -height);
showAnimation.setDuration(500);
showAnimation.start();
}
}
The Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/slidelist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:clipToPadding="false"
tools:context=".ui.slidelist.SlideListFragment">
<android.support.constraint.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.8" />
<android.support.constraint.ConstraintLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#FF0000"
android:clipChildren="false"
android:clipToPadding="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/guideline">
<LinearLayout
android:id="#+id/list_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/list_to_slide"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
<Button
android:id="#+id/slide_up_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="SlideUp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The Adapter
public class DummyListAdapter extends RecyclerView.Adapter<DummyListAdapter.ViewHolder> {
private WeakReference<Context> mContext;
private ArrayList<DummyModel> data;
public DummyListAdapter(Context ctx) {
mContext = new WeakReference<>(ctx);
}
#NonNull
#Override
public DummyListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.dummy_list_item, parent, false);
DummyListAdapter.ViewHolder vh = new DummyListAdapter.ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(#NonNull DummyListAdapter.ViewHolder holder, int position) {
// get element from your dataset at this position
final DummyModel item = data.get(position);
// replace the contents of the view with that element
holder.labelTV.setText(item.getText());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext.get(), "Item Clicked: "+ item.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return data != null ? data.size() : 0;
}
public void refreshItems(ArrayList<DummyModel> items) {
this.data = items;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView labelTV;
public ViewHolder(View itemView) {
super(itemView);
this.labelTV = itemView.findViewById(R.id.label_tv);
}
}
}
The List Item Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/label_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="TextView"
android:textSize="20sp"
android:textColor="#0000FF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
What is happening in this case?
UPDATE
I am doing some debug and I noticed that the problem is because the end position is outside the list container. If I translate inside the container, it works properly. So my new question is: how can I translate a view outside of the container, while still having the click events triggered?
Basically, I just gave up on this approach. I changed my layout so it list has space to show up inside its container.
I am making an android chat app. I have a recyclerview to show messages. i have two different layouts for messages, one for sent and one for received. my recyclerview doesnt throw any error but is doesnt show anything on the screen.
This is my adapter class :
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Chat> items;
private final int USER = 1, CONTACT = 2;
// Provide a suitable constructor (depends on the kind of dataset)
public ChatAdapter(List<Chat> items) {
this.items = items;
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return this.items.size();
}
#Override
public int getItemViewType(int position) {
if(items.get(position).getType()==1)
return USER;
else
return CONTACT;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
RecyclerView.ViewHolder viewHolder;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (viewType){
case USER:
View v1 = inflater.inflate(R.layout.chat_item_user, viewGroup, false);
viewHolder = new ViewHolder1(v1);
break;
default:
View v2 = inflater.inflate(R.layout.chat_item_contact, viewGroup, false);
viewHolder = new ViewHolder1(v2);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (viewHolder.getItemViewType()) {
case USER:
ViewHolder1 vh1 = (ViewHolder1) viewHolder;
configureViewHolder1(vh1, position);
break;
default:
ViewHolder2 vh2 = (ViewHolder2) viewHolder;
configureViewHolder2(vh2, position);
break;
}
}
public void configureViewHolder1(ViewHolder1 viewHolder, int position){
Chat chat = items.get(position);
viewHolder.getTv().setText(chat.getMsg());
}
public void configureViewHolder2(ViewHolder2 viewHolder, int position){
Chat chat = items.get(position);
viewHolder.getTv().setText(chat.getMsg());
}
}
This is my Chat class:
public class Chat {
private int type;
private String msg;
private long time;
public Chat(int type,long time,String msg){this.type = type; this.msg = msg; this.time = time;}
public int getType(){return type;}
public void setType(int type){this.type = type;}
public String getMsg(){return msg;}
public void setMsg(String msg){this.msg = msg;}
public long getTime(){return time;}
public void setTime(long time){this.time = time;}
}
This my layout containing the recylcerview :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="368dp"
android:layout_height="59dp"
android:layout_marginEnd="9dp"
android:layout_marginStart="7dp"
android:layout_marginTop="16dp"
android:background="#android:color/holo_green_light"
android:text="TextView"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="368dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="394dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
<EditText
android:id="#+id/editText8"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginStart="8dp"
android:layout_marginTop="1dp"
android:ems="10"
android:inputType="textMultiLine"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/recyclerView" />
<ImageButton
android:id="#+id/imageButton"
android:layout_width="53dp"
android:layout_height="54dp"
android:scaleType="fitCenter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/recyclerView"
app:srcCompat="#drawable/logo_arrow" />
These are my two layouts:
a. chat_item_contact
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView5"
android:layout_width="323dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="45dp"
android:layout_marginTop="16dp"
android:background="#android:color/holo_green_light"
android:paddingLeft="10dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
b. chat_item_user
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView4"
android:layout_width="329dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginEnd="48dp"
android:layout_marginStart="7dp"
android:layout_marginTop="7dp"
android:background="#android:color/holo_green_light"
android:paddingLeft="10dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I've done something similar, you should focus mostly on getItemViewType
Here is how I do (also I suggest you to use RecyclerView instead of ListView)
#Override
public int getItemViewType(int position){
if (/*your condition based on message received or sent*/) {
return VIEW_MESSAGE_RECEIVED;
}
else {
return VIEW_MESSAGE_SENT;
}
}
After, you just check what getItemViewType has returned
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_MESSAGE_RECEIVED) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_message_item_received, parent, false);
return new ChatAdapter.MyViewHolder(view);
}else {
View eventDataView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_message_item_sent, parent, false);
return new ChatAdapter.MyViewHolder(view);
}
}
Try this code..
remove listitem null check because once value is assign after that it not getting null.
add also add one more things if one layout is show than other is gone at time two layout not show to good..
if (currentChat.getType() == 1) {
listItem1 = LayoutInflater.from(context).inflate(R.layout.chat_item_user, parent, false);
listItem1.setVisibility(View.VISIBLE);
listItem2.setVisibility(View.GONE);
} else {
listItem2 = LayoutInflater.from(context).inflate(R.layout.chat_item_contact, parent, false);
listItem2.setVisibility(View.VISIBLE);
listItem1.setVisibility(View.GONE);
}