ImageView внутри ListView не отображается после изменения основного макета с Constraint на Relative - PullRequest
0 голосов
/ 11 апреля 2020

как сказано в названии. У меня есть ListView внутри макета основной деятельности. Вначале это был ConstraintLayout, но я решил сделать его RelativeLayout, и после этого мой ImageView внутри row_item исчез, и я не могу его вернуть, я попробовал много ответов, но ни один не помог мне.

Вот код ListAdapter:

public class ListAdapter extends ArrayAdapter<Product> {
private int resourceLayout;
private Context mContext;
private List<Product> items;
private AlertDialog.Builder alert;
EditText edittext;

public ListAdapter(Context context, int resource, List<Product> items) {
    super(context, resource, items);
    this.items = items;
    this.resourceLayout = resource;
    this.mContext = context;
}



@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    alert = new AlertDialog.Builder(mContext);
    View v = convertView;
    if (v == null) {
        LayoutInflater vi;
        vi = LayoutInflater.from(mContext);
        v = vi.inflate(resourceLayout, null);
    }

    final Product p = getItem(position);
    ImageView deleteImage = (ImageView) v.findViewById(R.id.delete_image);
    deleteImage.setVisibility(View.VISIBLE);

    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            edittext = new EditText(mContext);
            edittext.setPaddingRelative(5,10,10,5);
            edittext.setHint("New Quantity");
            Log.d("DATABASE", " "+ position);
            new AlertDialog.Builder(mContext)
                    .setTitle("Are you sure?")
                    .setView(edittext)
                    .setMessage("Do you want to change the quantity of product " + p.getName())
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String editedValue = edittext.getText().toString();
                            if (TextUtils.isEmpty(edittext.getText())){
                                Toast.makeText(mContext, "You need to specify a quantity", LENGTH_SHORT).show();
                            } else {
                                if (Integer.parseInt(editedValue) == 0 && Integer.parseInt(editedValue) > 100){
                                    Toast.makeText(mContext, "Quantity should be greater than 0 and less than 100", LENGTH_SHORT).show();
                                }else {
                                    p.setQuantity(Integer.parseInt(editedValue));  /// Ceva nu merge bine aici, schimba valoarea desi e 0
                                    notifyDataSetChanged();
                                }
                            }

                        }
                    })
                    .setNegativeButton("No", null)
                    .show();
        }
    });

    deleteImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(mContext)
                    .setIcon(R.drawable.del_button)
                    .setTitle("Are you sure?")
                    .setMessage("Do you want to delete the product " + p.getName() + " from you shopping cart ?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            items.remove(position);
                            notifyDataSetChanged();
                        }
                    })
                    .setNegativeButton("No", null)
                    .show();
        }
    });




    if (p != null) {
        TextView tt1 = (TextView) v.findViewById(R.id.product_name);
        TextView tt2 = (TextView) v.findViewById(R.id.product_quantity);
        TextView tt3 = (TextView) v.findViewById(R.id.product_price);

        if (tt1 != null) {
            tt1.setText(p.getName());
        }

        if (tt2 != null) {
            tt2.setText(String.valueOf(p.getQuantity()));
        }

        if (tt3 != null) {
            tt3.setText(String.valueOf(p.getPrice()*p.getQuantity()));
        }
    }

    return v;
}

Вот мой макет для row_item

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:andorid="http://schemas.android.com/tools"
android:orientation="vertical"
android:padding="10dp">

<TextView
    android:id="@+id/product_name"
    android:textSize="25dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:text="Product Name"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:textColor="@android:color/black" />


<TextView
    android:id="@+id/product_quantity"
    android:textSize="20dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/product_name"
    android:text="Quantity:"
    android:textColor="@android:color/black" />

<TextView
    android:id="@+id/product_price"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@id/product_name"
    android:layout_marginLeft="45dp"
    android:layout_centerInParent="true"
    android:src="@android:drawable/ic_dialog_info"
    android:text="Price"
    android:textSize="26dp" />

<ImageView
    android:id="@+id/delete_image"
    android:layout_width="42dp"
    android:layout_height="42dp"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    android:layout_marginEnd="25dp"
    android:clickable="true"
    android:focusable="true"
    andorid:src="@drawable/del_button" />

   </RelativeLayout>

А вот основной макет:

<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="match_parent"
android:background="#00ff00"
android:padding="15dp">

<Button
    android:id="@+id/btn_scan"
    android:layout_width="105dp"
    android:layout_height="67dp"
    android:layout_alignParentRight="true"
    android:layout_marginRight="30dp"
    android:text="SCAN"
    android:textAlignment="center"
    android:textColor="@color/colorPrimary"
    android:textSize="26dp"
    />

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="570dp"
    android:layout_marginStart="1dp"
    android:layout_marginTop="1dp"
    android:layout_marginEnd="1dp"
    android:layout_marginBottom="1dp"
    android:layout_below="@id/btn_scan" />

</RelativeLayout>

Как я уже сказал, до изменения моего основного макета с Constraint на Relative все работало нормально. Не уверен, в чем проблема, также, у ImageView был метод onClick, который удалял строку при нажатии после отображения AlertDialog. Который работал нормально. Не уверен, в чем может быть проблема, я искал ответы, но никто не помог мне. Также вот моя папка с фотографией: enter image description here

1 Ответ

0 голосов
/ 11 апреля 2020

Скорее всего, проблема в атрибуте android:src, так как он не поддерживает векторные рисунки, которые могут быть загружены только через app:srcCompat

Так что, пожалуйста, замените android:src на app:srcCompat ; следовательно, ImageView в вашем макете элемента списка будет иметь вид:

<ImageView
    android:id="@+id/delete_image"
    android:layout_width="42dp"
    android:layout_height="42dp"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    android:layout_marginEnd="25dp"
    android:clickable="true"
    android:focusable="true"
    app:srcCompat="@drawable/del_button" />

, и в этом случае может появиться предупреждение, требующее добавления нижеприведенного фрагмента в файл Gradle, уровень модуля в android {.. .}

android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
    }  
}  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...