recyclerview items size not the same size in layout - android

I'm trying to make a nested recyclerview with multiple items and after finishing the adatper and design and going in testing I got this in the emulator
I didn't understand why items appears like that, the items not the same height and width which I make it for the design of it's layout.
here is the code for recyclerview setup
mRecyclerView.setHasFixedSize(true);
adapter = new CheckoutMainRecyAdapter(CheckOutActivity.this, allSampleData);
mRecyclerView.setLayoutManager(new LinearLayoutManager(CheckOutActivity.this));
mRecyclerView.setAdapter(adapter);
and here is the adapter code
public class CheckoutMainRecyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<CheckoutMainModel> dataList;
private Context mContext;
public CheckoutMainRecyAdapter(Context context, ArrayList<CheckoutMainModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view;
switch (i) {
case Constants.type_checkout_address:
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.checkout_address_item, null);
CheckoutMainRecyAdapter.AddressItemHolder mho = new CheckoutMainRecyAdapter.AddressItemHolder(view);
return mho;
case Constants.type_checkout_policy:
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.checkout_policy_item, null);
CheckoutMainRecyAdapter.TermsItemHolder pro = new CheckoutMainRecyAdapter.TermsItemHolder(view);
return pro;
case Constants.type_checkout_payment:
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.checkout_payment_item, null);
CheckoutMainRecyAdapter.PaymentItemHolder proO = new CheckoutMainRecyAdapter.PaymentItemHolder(view);
return proO;
case Constants.type_checkout_button:
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.checkout_button_item, null);
CheckoutMainRecyAdapter.ButtonItemHolder proOO = new CheckoutMainRecyAdapter.ButtonItemHolder(view);
return proOO;
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder itemRowHolder, final int i) {
CheckoutMainModel newCheckoutItemsModel = dataList.get(i);
Log.d("itemType", String.valueOf(newCheckoutItemsModel.getType()));
Log.d("lastitem", ":ii:" + String.valueOf(i));
Activity activity = (Activity) mContext;
switch (newCheckoutItemsModel.getType()) {
case Constants.type_checkout_button:
((ButtonItemHolder) itemRowHolder).confirmBtn.setText("confirm btn");
((ButtonItemHolder) itemRowHolder).confirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent3 = new Intent(mContext, CategoryActivity.class);
intent3.putExtra("from", "Home");
mContext.startActivity(intent3);
}
});
break;
case Constants.type_checkout_address:
((AddressItemHolder) itemRowHolder).addressTitle.setText("adress title");
((AddressItemHolder) itemRowHolder).addressDetails.setText("addressDetails");
if (dataList.get(i).getAddressModels().size()<=1){
((AddressItemHolder) itemRowHolder).changeBtn.setVisibility(View.GONE);
}
((AddressItemHolder) itemRowHolder).addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
((AddressItemHolder) itemRowHolder).changeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
break;
case Constants.type_checkout_payment:
Log.d("lastitem", ":iin:" + String.valueOf(i));
final String sectionName = dataList.get(i).getTitle();
((PaymentItemHolder) itemRowHolder).paymentTitle.setText(sectionName);
((PaymentItemHolder) itemRowHolder).cashCL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent3 = new Intent(mContext, CategoryActivity.class);
intent3.putExtra("from", "Home");
mContext.startActivity(intent3);
//Toast.makeText(v.getContext(), sectionName, Toast.LENGTH_SHORT).show();
}
});
((PaymentItemHolder) itemRowHolder).onlinePaymentCl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent3 = new Intent(mContext, CategoryActivity.class);
intent3.putExtra("from", "Home");
mContext.startActivity(intent3);
}
});
break;
case Constants.type_checkout_policy:
final String policySectionName = dataList.get(i).getTitle();
final String policySectionDetails = dataList.get(i).getApp_policy();
((TermsItemHolder) itemRowHolder).termsTitle.setText(policySectionName);
((TermsItemHolder) itemRowHolder).termsDetails.setText(policySectionDetails);
((TermsItemHolder) itemRowHolder).accept_policy.setOnCheckedChangeListener
(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
}
);
break;
}
}
#Override
public int getItemViewType(int position) {
CheckoutMainModel newCheckoutItemsModel = dataList.get(position);
if (newCheckoutItemsModel != null) {
return newCheckoutItemsModel.getType();
}
// return super.getItemViewType(position);
return 0;
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
#Override
public long getItemId(int position) {
return position;
}
public class AddressItemHolder extends RecyclerView.ViewHolder {
protected TextView addressTitle;
protected TextView addressDetails;
protected RecyclerView recycler_view_list;
protected Button changeBtn;
protected Button addBtn;
public AddressItemHolder(View view) {
super(view);
this.addressTitle = (TextView) view.findViewById(R.id.addressTitleCheckout);
this.recycler_view_list = (RecyclerView) view.findViewById(R.id.address_rv_checkout);
this.addressDetails = (TextView) view.findViewById(R.id.address_details);
this.addBtn = view.findViewById(R.id.add_address_btn);
this.changeBtn = view.findViewById(R.id.change_address_btn);
}
}
public class TermsItemHolder extends RecyclerView.ViewHolder {
protected TextView termsTitle;
protected TextView termsDetails;
protected CheckBox accept_policy;
public TermsItemHolder(View view) {
super(view);
this.termsTitle = (TextView) view.findViewById(R.id.policy_title);
this.termsDetails = (TextView) view.findViewById(R.id.policy_messge);
this.accept_policy = view.findViewById(R.id.checkBox_policy);
}
}
public class ButtonItemHolder extends RecyclerView.ViewHolder {
protected Button confirmBtn;
public ButtonItemHolder(View view) {
super(view);
this.confirmBtn = view.findViewById(R.id.checkout_item_btn);
}
}
public class PaymentItemHolder extends RecyclerView.ViewHolder {
protected TextView paymentTitle;
protected TextView cashText;
protected TextView creditText;
protected ConstraintLayout cashCL;
protected ConstraintLayout onlinePaymentCl;
public PaymentItemHolder(View view) {
super(view);
this.paymentTitle = (TextView) view.findViewById(R.id.payment_method_title);
this.cashText = (TextView) view.findViewById(R.id.cash_tv);
this.creditText = (TextView) view.findViewById(R.id.onlinePayment_tv);
this.cashCL = view.findViewById(R.id.cash_cl);
this.onlinePaymentCl = view.findViewById(R.id.credit_cl);
}
}
}
and here the layouts of recyclerview items
first item
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="-10dp"
app:cardCornerRadius="4dp"
app:cardElevation="0.7dp"
app:cardMaxElevation="1dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
app:contentPaddingBottom="0dp">
<android.support.constraint.ConstraintLayout
android:background="#color/colorGray"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.constraint.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<TextView
android:id="#+id/payment_method_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/deliver_to"
android:textColor="#color/colorButtonRed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/addressTitleCheckout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="المنزل"
app:layout_constraintEnd_toStartOf="#+id/add_address_btn"
app:layout_constraintStart_toEndOf="#+id/payment_method_title"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/address_details"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="شارع طلعت حرب"
app:layout_constraintEnd_toStartOf="#+id/add_address_btn"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addressTitleCheckout" />
<Button
android:id="#+id/change_address_btn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="#drawable/dots_border_bg"
android:text="#string/change_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/add_address_btn" />
<Button
android:id="#+id/add_address_btn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="#drawable/dots_border_bg"
android:text="#string/add_address_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.RecyclerView
android:id="#+id/address_rv_checkout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/change_address_btn" />
</android.support.constraint.ConstraintLayout>
second item
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="-10dp"
app:cardCornerRadius="4dp"
app:cardElevation="0.7dp"
app:cardMaxElevation="1dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
app:contentPaddingBottom="0dp">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:background="#color/colorGray"
android:layout_height="match_parent">
<android.support.constraint.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<TextView
android:id="#+id/payment_method_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/payment_method"
android:textColor="#color/colorButtonRed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.constraint.ConstraintLayout
android:id="#+id/cash_cl"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/payment_method_title">
<TextView
android:id="#+id/cash_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="#string/cash_payment"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/cash_tv"
app:layout_constraintTop_toTopOf="parent"
card_view:srcCompat="#drawable/iv_cash" />
</android.support.constraint.ConstraintLayout>
<android.support.constraint.ConstraintLayout
android:id="#+id/credit_cl"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/payment_method_title">
<TextView
android:id="#+id/onlinePayment_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="#string/online_payment"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/onlinePayment_tv"
app:layout_constraintTop_toTopOf="parent"
card_view:srcCompat="#drawable/iv_online_payment" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
third item
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="-10dp"
app:cardCornerRadius="4dp"
app:cardElevation="0.7dp"
app:cardMaxElevation="1dp"
app:cardPreventCornerOverlap="true"
app:cardUseCompatPadding="true"
app:contentPaddingBottom="0dp">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:background="#color/colorGray"
android:layout_height="match_parent">
<android.support.constraint.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
<TextView
android:id="#+id/policy_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/terms"
android:textColor="#color/colorButtonRed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/policy_messge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/delivery_fee_cost_terms"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/policy_title" />
<CheckBox
android:id="#+id/checkBox_policy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:checked="true"
android:text="#string/yes"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/policy_messge" />
</android.support.constraint.ConstraintLayout>
and here is the activity layout which recyclerview in
<?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">
<android.support.v7.widget.RecyclerView
android:id="#+id/checkout_rv"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/checkout_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#drawable/btn_bg_no_radius"
android:text="#string/cart_details_submit"
android:textColor="#color/white"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>

You have to supply the recycler as the root to the inflate method, so that the inflated view gets the correct layout parameters from the parent
You have to set attachToRoot to false, because the recycler view handles the attaching.
Example:
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.your_layout, viewGroup, false);

Related

RecyclerView that using GridLayoutManager with background makes different heights visible

I've made an adapter with a layout like the one I share below. it went well but, the appearance of each item became untidy.
Here is my code :
public class TableRecyclerAdapter extends RecyclerView.Adapter<TableRecyclerAdapter.ViewHolder> {
private ArrayList<TableModel> data;
private Context context;
private Fragment fragment;
private Dialog dialog;
public TableRecyclerAdapter(Context context, ArrayList<TableModel> data, Fragment fragment, Dialog dialog) {
this.context = context;
this.data = data;
this.fragment = fragment;
this.dialog = dialog;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.item_table, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvTable.setText(data.get(position).getName());
holder.tvState.setText(data.get(position).getStateString());
holder.bg.setBackgroundColor(Color.parseColor(data.get(position).getWarna()));
holder.tvHtml.setText(Html.fromHtml(data.get(position).getShortInfoHtml()));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public int getItemCount() {
return data.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView paid;
private TextView tvTable, tvHtml, tvState;
private ConstraintLayout bg;
public ViewHolder(View itemView) {
super(itemView);
tvTable = itemView.findViewById(R.id.tvTable);
tvHtml = itemView.findViewById(R.id.tvHtml);
bg = itemView.findViewById(R.id.bg);
tvState = itemView.findViewById(R.id.tvState);
paid = itemView.findViewById(R.id.ivPaid);
}
}
}
This is for layout item
<?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"
android:layout_margin="4dp"
app:cardCornerRadius="10dp"
app:cardElevation="3dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/bg"
android:layout_width="match_parent"
android:background="#drawable/border_button_green"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_marginStart="12dp"
android:background="#drawable/border_transparent_table"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/tvState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="This text"
android:textColor="#color/color_primary"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:id="#+id/tvTable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="25dp"
android:paddingStart="12dp"
android:paddingEnd="12dp"
android:text="7"
android:textColor="#color/color_primary"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvHtml"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:paddingBottom="12dp"
android:text="Example Text"
android:textColor="#color/color_primary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tvTable" />
<ImageView
android:id="#+id/ivPaid"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="4dp"
android:src="#drawable/paid"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
It makes my recyclerview have different heights depending on the text.
I want the items to be the same height per row (maximum height in the row)
Sorry for my english. I hope someone can help me. Thank you

Andriod Studio ListView doesn't update itself

I have ListView and my own adapter. ListView item consists of TextView, icon image and image "trash can"(simply "trash"). The problem is when i click on any item it should be deleted but in fact the last item of ListView disappears. I checked ArrayList and the item I clicked on is deleted from there.
Also when i try to add new item the program just restore previous items and if all initial items are displayed and i try to add new the program crashes. Although in ArrayList items are added correctly.
Activity code
public class MyItemsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_items);
myItemsList = findViewById(R.id.ListOfMyItems);
myItemsAdapter.arrayList.add(new MyItems("Keys", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("Wallet", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("Physics", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("umovnyy vasyl", R.drawable.plus));
myItemsAdapter.arrayList.add(new MyItems("Smartphone)", R.drawable.plus));
for (int i = 0; i<100; i++){
arrayList.add(new MyItems("Max)", R.drawable.plus));
}
myItemsList.addFooterView(new ImageView(this));
myItemsList.addHeaderView(new ImageView(this));
myItemsList.setAdapter(myItemsAdapter);
for (int i = 0; i<100; i++){
myItemsAdapter.arrayList.remove((5));
}
arrayList.add(new MyItems("Maxx)", R.drawable.plus));
myItemsAdapter.notifyDataSetChanged();
myItemsAdapter.notifyDataSetInvalidated();
myItemsList.setOnItemClickListener((parent, view, position, id) -> {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_SHORT)
.show();
myItemsAdapter.arrayList.remove((position-1));
myItemsAdapter.notifyDataSetChanged();
myItemsList.invalidateViews();
myItemsAdapter.notifyDataSetInvalidated();
});
}
ListView myItemsList;
ArrayList<MyItems> arrayList = new ArrayList<>();
MyItemsAdapter myItemsAdapter = new MyItemsAdapter(MyItemsActivity.this, arrayList);
public void addNewItem(View view) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MyItemsActivity.this);
dialog.setView(R.layout.add_new_item);
AlertDialog alertDialog = dialog.create();
ListView a = alertDialog.getListView();
alertDialog.show();
myItemsList.invalidateViews();
}
public void addNewItemButtonClicked(View view){
LayoutInflater inflater = getLayoutInflater();
View v = inflater.inflate(R.layout.add_new_item, null);
EditText nameOfItem = v.findViewById(R.id.nameOfItem);
arrayList.add(new MyItems(nameOfItem.getText().toString(), R.drawable.forwardbutton));
myItemsAdapter.notifyDataSetChanged();
myItemsAdapter.notifyDataSetInvalidated();
}
public void notificationClicked(View view){
Toast.makeText(getApplicationContext(),
"Notification clicked", Toast.LENGTH_SHORT)
.show();
}
public void openMenu(View view) {
Intent intent = new Intent(getBaseContext(), MenuActivity.class);
startActivity(intent);
}
}
Adapter
class MyItemsAdapter extends BaseAdapter {
ArrayList<MyItems> arrayList;
Context context;
public MyItemsAdapter(Context context, ArrayList<MyItems> arrayList) {
this.arrayList=arrayList;
this.context=context;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
observer.onChanged();
super.registerDataSetObserver(observer);
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
super.unregisterDataSetObserver(observer);
observer.onInvalidated();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public MyItems getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final MyItems myItems = arrayList.get(position);
if(convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(R.layout.example_of_list_of_items, parent, false);
TextView nameOfItem = convertView.findViewById(R.id.exampleTextView);
ImageView itemCircle = convertView.findViewById(R.id.exampleImageViewIcon);
ImageView trash = convertView.findViewById(R.id.exampleImageViewTrash);
nameOfItem.setText(myItems.itemName);
itemCircle.setImageResource(myItems.itemImage);
trash.setImageResource(R.drawable.trash);
trash.setOnClickListener(v -> {
Toast.makeText(context, "lol "+position, Toast.LENGTH_SHORT).show();
arrayList.remove(position);
notifyDataSetChanged();
notifyDataSetInvalidated();
});
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return arrayList.size();
}
#Override
public boolean isEmpty() {
return false;
}
}
MyItems code
class MyItems {
String itemName;
int itemImage;
public MyItems(String itemName, int image) {
this.itemName = itemName;
this.itemImage = image;
}
}
Example of item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/exampleTextView"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="85dp"
android:fadingEdge="horizontal|vertical"
android:layoutDirection="inherit"
android:lineSpacingExtra="14sp"
android:text="TextView"
android:textAlignment="textStart"
android:textColor="#000000"
android:textSize="20sp"
app:autoSizeMaxTextSize="20sp"
app:autoSizeMinTextSize="8sp"
app:layout_constraintEnd_toStartOf="#+id/exampleImageViewTrash"
app:layout_constraintStart_toEndOf="#+id/exampleImageViewLeft"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/exampleImageViewLeft"
android:layout_width="25dp"
android:layout_height="23dp"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#mipmap/ic_launcher_round" />
<ImageView
android:id="#+id/exampleImageViewTrash"
android:layout_width="49dp"
android:layout_height="47dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="20dp"
android:cropToPadding="true"
android:fitsSystemWindows="true"
android:focusableInTouchMode="false"
android:focusable="false"
android:clickable="false"
android:scaleType="centerInside"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/trash" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_begin="70dp"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Code of main screen
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="99dp">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_begin="127dp"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/myItemsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/my_items"
android:textColor="#000000"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/menuImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:clickable="true"
android:focusable="true"
android:onClick="openMenu"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/menu" />
<ImageView
android:id="#+id/notificationImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:clickable="true"
android:focusable="true"
android:onClick="notificationClicked"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/notification" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/ListOfMyItems"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="100dp"
android:alwaysDrawnWithCache="true"
android:animateLayoutChanges="true"
android:choiceMode="singleChoice"
android:clickable="false"
android:clipToPadding="false"
android:descendantFocusability="beforeDescendants"
android:dividerHeight="1dp"
android:footerDividersEnabled="true"
android:headerDividersEnabled="true"
android:isScrollContainer="true"
android:layoutDirection="ltr"
android:scrollbars="vertical"
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"
tools:listfooter="#android:layout/simple_list_item_1">
</ListView>
<LinearLayout
android:layout_width="409dp"
android:layout_height="70dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:focusable="auto"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ListOfMyItems">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true">
<TextView
android:id="#+id/addNewItemTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="-1dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="70dp"
android:clickable="true"
android:focusable="true"
android:onClick="addNewItem"
android:text="#string/add_new_item"
android:textColor="#000000"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/plusImageView"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/plusImageView"
android:layout_width="67dp"
android:layout_height="74dp"
android:layout_marginStart="56dp"
android:clickable="false"
android:focusable="true"
android:onClick="addNewItem"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/plus" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Code for AlertDialog adding new item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#FFFFFF">
<EditText
android:id="#+id/nameOfItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:ems="10"
android:hint="Enter name"
android:inputType="textPersonName"
android:singleLine="true"
android:textColor="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginTop="9dp"
android:background="#android:drawable/btn_default_small"
android:onClick="addNewItemButtonClicked"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/nameOfItem" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
Looks like your data is not properly updated inside the Adapter's getView method.
You should try to update the item inside the Adapter when contentView is not null.
For performance reason, there is a pattern called ViewHolder used inside the adapter. Refer to Android listview using ViewHolder for more info. Just create Holder when contentView is null and set the data when it isn't. Hope it helps.
P.S. ListView is considered deprecated. Use RecyclerView instead. It has already built-in ViewHolder pattern and is more flexible

Android ListView OnItemClickListener not working properly

I have created a simple ListView which has a child view. However, OnItemClickListener is not working.
Guys, can you tell me the issue here?
lvList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListData mLog = listAdapter.getItem(position);
Toast.makeText(JobsActivity.this, "Title: " + mLog.getTitle() + " Description: " + mLog.getDescription(), Toast.LENGTH_LONG).show();
}
});
public class JobsActivity extends Drawer {
public static final int MULTIPLE_PERMISSIONS = 10;
ListView lvList;
ArrayList<ListData> myList = new ArrayList<ListData>();
ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobs);
ButterKnife.bind(this);
askForPermission();
loadDrawer();
lvList = (ListView) findViewById(R.id.list);
listAdapter = new ListAdapter(JobsActivity.this, myList);
for (int i = 0; i<=5; i++){
ListData mLog = new ListData();
mLog.setTitle("test "+i);
mLog.setDescription("demo "+i);
mLog.setImage("https://via.placeholder.com/150");
myList.add(mLog);
}
listAdapter.notifyDataSetChanged();
lvList.setAdapter(listAdapter);
lvList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListData mLog = listAdapter.getItem(position);
Toast.makeText(JobsActivity.this, "Title: " + mLog.getTitle() + " Description: " + mLog.getDescription(), Toast.LENGTH_LONG).show();
}
});
}
Parent Listview
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:focusable="true"
android:clickable="true"
android:focusableInTouchMode="false"
tools:context=".JobsActivity"
tools:openDrawer="start">
<ProgressBar
android:id="#+id/main_progress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:elevation="2dp"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:padding="16dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="false"
android:clickable="true"
>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clickable="true"
android:divider="#android:color/transparent"
android:focusable="true"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Child Items
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/CardView.Light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:focusable="false"
android:focusableInTouchMode="false"
tools:context=".JobsActivity"
tools:ignore="ContentDescription">
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/customer_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:text="#string/customer_name"
android:textAppearance="#style/TextAppearance.AppCompat.Headline"
android:textColor="#color/colorPrimaryTextDefaultMaterialLight"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/customer_mobile_image" />
<TextView
android:id="#+id/mobile_model"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:text="#string/mobile_model"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#color/colorSecondaryTextDefaultMaterialLight"
app:layout_constraintTop_toBottomOf="#+id/customer_name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/customer_mobile_image" />
<ImageView
android:id="#+id/customer_mobile_image"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginEnd="16dp"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:color/darker_gray" />
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/action_button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="0dp"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:text="#string/show_location"
android:textColor="#color/colorPrimaryTextDefaultMaterialLight"
app:layout_constraintTop_toBottomOf="#+id/customer_mobile_image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:focusable="false"
android:focusableInTouchMode="false"
/>
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/btnOpen_pickup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:minWidth="0dp"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:text="#string/open_job"
android:textColor="#color/colorPrimaryTextDefaultMaterialLight"
app:layout_constraintTop_toTopOf="#+id/action_button_1"
app:layout_constraintStart_toEndOf="#+id/action_button_1" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
I have tried using Adapters it worked...
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ListViewHolder view = (ListViewHolder) convertView;
if (view == null) {
view = new ListViewHolder(context);
}
ListData log = getItem(position);
view.setLog(log);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("test item",myList.get(position).getTitle());
}
});
Button ShowMap = view.findViewById(R.id.btnShowMap);
ShowMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("test item",myList.get(position).getImage().toString());
}
});
return view;
}

Button in Fragment is unclickable in android studio

I am trying to have a button go from a fragment layout to an xml file. However when running the app, I can not click on the button. I've checked if I have to correct id. This is the case. Does someone know the answer why it won't trigger my onClickListener()? I feel like it is something small that I'm am missing, but I don't know exactly what. Thanks !
my class :
public class AccountFragment extends Fragment {
private FragmentActivity myContext;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private View RootView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
private static final String TAG = AccountFragment.class.getSimpleName();
private static final String ARG_SECTION_NUMBER = "section_number";
public static final int TAB_PRIVATE = 1;
public static final int TAB_CORP = 2;
public AccountFragment() {
}
public static AccountFragment newInstance(int sectionNumber) {
AccountFragment fragment = new AccountFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RootView = inflater.inflate(R.layout.fragment_account, container, false);
Log.i(TAG, "onCreateView()");
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(myContext.getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) RootView.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
//BUTTON
Button openSettingsButton = RootView.findViewById(R.id.open_settings);
openSettingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), PreferenceFragmentAccount.class);
startActivity(i);
}
});
return RootView;
}
#Override
public void onResume() {
Log.i(TAG, "onResume()");
super.onResume();
View view = getView();
if (view == null) {
Log.e(TAG, "view is null!");
return;
}
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String username=null;
String email=null;
String firstname=null;
String lastname=null;
String phoneNumber=null;
username = sharedPreferences.getString(USERNAME, null);
email = sharedPreferences.getString(EMAIL, null);
firstname = sharedPreferences.getString(FIRSTNAME, null);
lastname = sharedPreferences.getString(LASTNAME, null);
phoneNumber = sharedPreferences.getString(PHONE, null);
ImageView qrCode = view.findViewById(R.id.qr);
qrCode.setImageDrawable(getResources().getDrawable(R.drawable.ic_hourglass_full_teal_24dp));
if (TextUtils.isEmpty(username)) {
username = getString(R.string.no_name);
}
VCard vCard = new VCard(username)
.setEmail(email)
.setName(firstname + lastname)
.setPhoneNumber(phoneNumber);
WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
view.getHeight();
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int qrSize = (int) (0.8 * (double) Math.min(size.x, size.y));
setTextToTextViewOrHide(username, R.id.username, view);
setTextToTextViewOrHide(email, R.id.email, view);
setTextToTextViewOrHide(firstname, R.id.firstname, view);
setTextToTextViewOrHide(lastname, R.id.lastname, view);
setTextToTextViewOrHide(phoneNumber, R.id.phoneNumber, view);
new SetQrCodeTask().execute(new SetQrCodeTaskBundle(vCard, qrSize));
}
private void setTextToTextViewOrHide(String value, #IdRes int id, View view) {
TextView textView = view.findViewById(id);
if (TextUtils.isEmpty(value)) {
textView.setVisibility(View.GONE);
} else {
textView.setText(value);
}
}
private class SetQrCodeTaskBundle {
private VCard mVCard;
private int mQrSize;
SetQrCodeTaskBundle(VCard vCard, int qrSize) {
mVCard = vCard;
mQrSize = qrSize;
}
VCard getVCard() {
return mVCard;
}
int getQrSize() {
return mQrSize;
}
}
private class SetQrCodeTask extends AsyncTask<SetQrCodeTaskBundle, Void, Bitmap> {
private final String TAG = SetQrCodeTask.class.getSimpleName();
#Override
protected Bitmap doInBackground(SetQrCodeTaskBundle... setQrCodeTaskBundles) {
Log.d(TAG, "Generate QR code");
return QRCode
.from(setQrCodeTaskBundles[0].getVCard())
.withColor(0xFF000000, 0x00000000)
.withSize(setQrCodeTaskBundles[0].getQrSize(), setQrCodeTaskBundles[0].getQrSize())
.withHint(EncodeHintType.CHARACTER_SET, "UTF-8")
.bitmap();
}
#Override
protected void onPostExecute(Bitmap bitmap) {
Log.d(TAG, "Set QR code");
ImageView qrCode = getView().findViewById(R.id.qr);
qrCode.setImageBitmap(bitmap);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a ContactInfoFragment (defined as a static inner class below).
return AccountFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
}
}
My xml in the layout folder:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:fillViewport="true"
tools:context=".displayClasses.AccountScreen.AccountFragment">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/username"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:textColor="#color/primary_dark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Name"
android:inputType="textPersonName"
android:summary="%s"
android:icon="#drawable/ic_person_teal_24dp"
/>
<TextView
android:id="#+id/email"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/username"
tools:text="E-mail" />
<TextView
android:id="#+id/firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email"
tools:text="First name" />
<TextView
android:id="#+id/lastname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firstname"
tools:text="Last name" />
<TextView
android:id="#+id/phoneNumber"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/lastname"
tools:text="phoneNumber" />
<View
android:id="#+id/view"
android:layout_width="0dp"
android:layout_height="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/phoneNumber"
tools:ignore="MissingConstraints" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
<Button
android:id="#+id/open_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:paddingBottom="10dp"
android:text="#string/open_settings"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardView"
/>
<ImageView
android:id="#+id/qr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="24dp"
android:contentDescription="#string/qr_code"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/open_settings"
app:srcCompat="#drawable/ic_hourglass_full_teal_24dp" />
</android.support.constraint.ConstraintLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
I have check your code on Android Studio the code is perfect but one mistake is there as you have set Viewpager above parent RelativeLayout as match parent hence you are not getting button to click but if you refactor Viewpager below the button the you are able to get click.
Here is what you can do. I have AndroidX installed so codeis in that
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/username"
style="#style/TextAppearance.AppCompat.Large"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:icon="#drawable/ic_person_teal_24dp"
android:inputType="textPersonName"
android:summary="%s"
android:textColor="#color/primary_dark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Name" />
<TextView
android:id="#+id/email"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/username"
tools:text="E-mail" />
<TextView
android:id="#+id/firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email"
tools:text="First name" />
<TextView
android:id="#+id/lastname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firstname"
tools:text="Last name" />
<TextView
android:id="#+id/phoneNumber"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/lastname"
tools:text="phoneNumber" />
<View
android:id="#+id/view"
android:layout_width="0dp"
android:layout_height="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/phoneNumber"
tools:ignore="MissingConstraints" />
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
<Button
android:id="#+id/open_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:text="#string/open_settings"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="43dp" />
<ImageView
android:id="#+id/qr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="24dp"
android:contentDescription="#string/qr_code"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/open_settings"
app:srcCompat="#drawable/ic_hourglass_full_teal_24dp" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="554dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout_editor_absoluteY="105dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
why you don't use butterknife
add to gradle ->
implementation 'com.jakewharton:butterknife:9.0.0-rc2'
annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-rc2'
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RootView = inflater.inflate(R.layout.fragment_account, container, false);
ButterKnife.bind(this, RootView );
...
return RootView;
}
#OnClick(R.id.open_settings)
public void btn(){
Intent i = new Intent(getContext(), PreferenceFragmentAccount.class);
startActivity(i);
}
okey so you can change source like this :
Button openSettingsButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RootView = inflater.inflate(R.layout.fragment_account, container, false);
Log.i(TAG, "onCreateView()");
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(myContext.getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) RootView.findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
//BUTTON
openSettingsButton = RootView.findViewById(R.id.open_settings);
return RootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
openSettingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), PreferenceFragmentAccount.class);
startActivity(i);
}
});
}

change ImageView based on the clicked spinner item its not working

I have 2 two images (item1.png and item2.png) and I want to show each image in a ImageView when the items on the spinner are clicked. When the "item1" in the spinner is selected I want to show the "item1.png" image and the same for the "item2".
Im trying to do this with the code below but its no working. Do you know what is the issue?
On MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
String string = String.valueOf(spinner.getSelectedItem());
final ImageView image = (ImageView)findViewById(R.id.image);
int image1 = R.drawable.item1;
int image2 = R.drawable.item2;
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//spinner.
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2) {
if (arg2 == 0) {
image.setImageResource(R.drawable.item1);
} else {
image.setImageResource(R.drawable.item2);
}
}
}
}
}
Activity xml:
<?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="com.example.ricardorei.tpc.MainActivity">
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Button"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="199dp"
android:layout_marginRight="58dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginEnd="58dp" />
<ImageView
android:id="#+id/image"
android:layout_width="0dp"
android:layout_height="220dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:srcCompat="#drawable/item1" />
<TextView
android:id="#+id/textView2"
android:layout_width="321dp"
android:layout_height="28dp"
android:layout_marginBottom="32dp"
android:layout_marginLeft="32dp"
android:layout_marginRight="32dp"
android:text="Are Awesome!"
app:layout_constraintBottom_toTopOf="#+id/imageView2"
app:layout_constraintHorizontal_bias="0.517"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp" />
<TextView
android:id="#+id/textView3"
android:layout_width="295dp"
android:layout_height="28dp"
android:text="TextView"
app:layout_constraintBaseline_toBaselineOf="#+id/button3"
android:layout_marginLeft="32dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginStart="32dp" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="134dp"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:entries="#array/spinner_values"
app:layout_constraintHorizontal_bias="0.522"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</android.support.constraint.ConstraintLayout>
Try to change OnItemSelectedListener like below:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
image.setImageResource(R.drawable.item1);
break;
case 1:
image.setImageResource(R.drawable.item2);
break;
default:
//Default image
//image.setImageResource(R.drawable.item2);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Categories

Resources