Как получить элементы edittext и imageview из одного адаптера в Android? - PullRequest
0 голосов
/ 20 декабря 2018

Я пытаюсь создать приложение #android, которое будет отображать на изображении #gridview, которое пользователь выбрал в своей галерее, и ниже каждого из изображений я помещаю текст редактирования.Gooal - позволить пользователю изменять, скажем, цену каждого изображения через текст редактирования.Моя проблема в том, что я не могу получить эти данные, чтобы сохранить их.

Поскольку в моем адаптере я создаю 2 типа элементов (imageView и EditText), мне не совсем понятно, как получить все изображения и ихсоответствующий текст.Я попытался gvGallery.setOnItemClickListener gridview, но не ответ.galleryAdapter.getItem (0) создает исключение IndexOutOfBoundsException

Между тем,

convertView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.i("gat", "onClick: "+ finalConvertView.getId());
        Log.i("gat", "Test: "+ holder.gPrice.getId());
    }
});

В адаптере дает мне результат при нажатии, но я все еще не могу получить желаемый результат (все изображения и соответствующиезначения editText)

Намерение открыть галерею изображений

Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);

startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);

My onActivityРезультат получения изображений из галереи телефона

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
    // When an Image is picked
        if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && null != data) {
            // Get the Image from data

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            imagesEncodedList = new ArrayList<String>();
            if(data.getData()!=null){

                Uri mImageUri=data.getData();

                // Get the cursor
                Cursor cursor = getContentResolver().query(mImageUri,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imageEncoded  = cursor.getString(columnIndex);
                cursor.close();

                ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                mArrayUri.add(mImageUri);
                galleryAdapter = new GalleryAdapter(getApplicationContext(), mArrayUri, gDefaultPrice);

                galleryAdapter.getItem(0);
                gvGallery.setAdapter(galleryAdapter);
                gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
                ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
                        .getLayoutParams();
                mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);

            } else {
                if (data.getClipData() != null) {
                    ClipData mClipData = data.getClipData();
                    ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                    for (int i = 0; i < mClipData.getItemCount(); i++) {

                        ClipData.Item item = mClipData.getItemAt(i);
                        Uri uri = item.getUri();
                        mArrayUri.add(uri);
                        // Get the cursor
                        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                        // Move to first row
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        imageEncoded  = cursor.getString(columnIndex);
                        imagesEncodedList.add(imageEncoded);
                        cursor.close();

                        galleryAdapter = new GalleryAdapter(getApplicationContext(), mArrayUri, gDefaultPrice);
                        gvGallery.setAdapter(galleryAdapter);
                        gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
                        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
                                .getLayoutParams();
                        mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);

                    }
                    Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
                }
            }
            Toast.makeText(ProfileActivity.this, "Item id is oooo", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

    super.onActivityResult(requestCode, resultCode, data);
}

GalleryAdapter.java

public class GalleryAdapter extends BaseAdapter {

private Context ctx;
private int pos;
private LayoutInflater inflater;
private ImageView ivGallery;
private EditText gPrice;
ArrayList<Uri> mArrayUri;
ArrayList<EditText> edit;
String defaultPrice;
public GalleryAdapter(Context ctx, ArrayList<Uri> mArrayUri, EditText gDefaultPrice) {

    this.ctx = ctx;
    this.mArrayUri = mArrayUri;
    try{
        this.defaultPrice = gDefaultPrice.getText().toString();
    }catch (NullPointerException e){
        this.defaultPrice = "0";
    }

}

@Override
public int getCount() {
    return mArrayUri.size();
}

@Override
public Object getItem(int position) {
    return mArrayUri.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, final ViewGroup parent) {
    final ViewHolder holder;
    pos = position;
    inflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // If holder not exist then locate all view from UI file.
    if (convertView == null) {
        // inflate UI from XML file
        convertView = inflater.inflate(R.layout.gv_item, parent, false);
        // get all UI view
        holder = new ViewHolder(convertView);
        // set tag for holder
        convertView.setTag(holder);
    } else {
        // if holder created, get tag from view
        holder = (ViewHolder) convertView.getTag();
    }

    //Initialize Edittext with default value
    holder.gPrice.setText(this.defaultPrice);
    holder.gPrice.setId(position);

    //Set image in imageView
    holder.imageView.setImageURI(mArrayUri.get(position));
    holder.imageView.setId(position);
    convertView.setId(position);

    //Test on click result
    final View finalConvertView = convertView;
    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("gat", "onClick: "+ finalConvertView.getId());
            Log.i("gat", "Test: "+ holder.gPrice.getId());

        }
    });

    return convertView;
}

private class ViewHolder {

    private ImageView imageView;
    private EditText gPrice;

    public ViewHolder(View v) {
        imageView = v.findViewById(R.id.ivGallery);
        gPrice = v.findViewById(R.id.gPrice);
    }
}
}

Я не знаю, будет ли это полезно, но ниже приведен соответствующий XML для макета gridview

activity_profile.xml

<?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/profile_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".ProfileActivity">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/sConstraint"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include layout="@layout/toolbar_layout" />

        <in.srain.cube.views.GridViewWithHeaderAndFooter
            android:id="@+id/gv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fadingEdge="none"
            android:focusable="false"
            android:horizontalSpacing="10dp"
            android:numColumns="auto_fit"
            android:scrollbarStyle="outsideOverlay"
            android:scrollbars="none"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/toolbar" />

    </android.support.constraint.ConstraintLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/profileNavigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header_layout"
        app:menu="@menu/drawer_menu" />
    </android.support.v4.widget.DrawerLayout>

gv_item.xml

<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
    android:layout_height="130dp"
    android:layout_width="match_parent"
    android:padding="10dp"
    android:id="@+id/ivGallery"
    android:src="@mipmap/ic_launcher_round"
    android:scaleType="fitXY"
    />

<TextView
    android:id="@+id/gTextview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/default_gap"
    android:layout_marginRight="@dimen/default_gap"
    android:text="Prix"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/ivGallery" />

<EditText
    android:id="@+id/gPrice"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="@dimen/default_gap"
    android:layout_marginLeft="@dimen/default_gap"
    android:ems="10"
    android:inputType="number"
    android:background="#94e7d039"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/gTextview" />

<View
    android:id="@+id/divider12"
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layout_marginBottom="@dimen/default_gap"
    android:background="?android:attr/listDivider" />

</LinearLayout>
...