Диалоговое окно для выбора изображения из галереи - PullRequest
0 голосов
/ 18 ноября 2018

Я пытаюсь показать диалоговое окно, в котором когда-либо нажимается кнопка ImageButton, а затем выбрать либо снимки из галереи, либо снять некоторые с камеры. Я уже пытаюсь выбрать изображение и вставить его в правильный вид изображения.

Прямо сейчас, нажав ImageButton (android: id = "@ + id / imageSelect"), откроется диалоговое окно, затем выберите «Выбрать из галереи», но вставьте изображение в (android: id = "@ + id / imageSelect1), который должен быть вставлен в (android: id = "@ + id / imageSelect). И когда я выбираю (android: id = "@ + id / imageSelect1), он просто перезаписывает изображение, поэтому (android: id =" @ + id / imageSelect) остается пустым

У меня ощущение, что что-то не так в классе SelectPhotoDialog.

Работа без диалогового окна работает нормально, но я бы хотел, чтобы эта опция выбиралась из камеры или галереи.

Вот мой xml-файл:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Image 1" />

        <ImageButton
            android:id="@+id/imageSelect"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:adjustViewBounds="true"
            android:background="@android:color/white"
            android:scaleType="centerCrop"
            />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Image 2" />

        <ImageButton
            android:id="@+id/imageSelect1"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:adjustViewBounds="true"
            android:background="@android:color/white"
            android:scaleType="centerCrop"
            />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Image 3" />

        <ImageButton
            android:id="@+id/imageSelect2"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:adjustViewBounds="true"
            android:background="@android:color/white"
            android:scaleType="centerCrop"
            />

        <EditText
            android:id="@+id/input_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:ems="10"
            android:hint="Title"
            android:inputType="textPersonName"
            android:padding="7dp"
            android:singleLine="true"
            android:textSize="14sp" />

        <EditText
            android:id="@+id/input_description"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="10dp"
            android:ems="10"
            android:hint="Description"
            android:inputType="textMultiLine"
            android:padding="7dp"
            android:textSize="14sp" />


        <EditText
            android:id="@+id/input_price"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:ems="10"
            android:hint="Price"
            android:inputType="numberDecimal"
            android:padding="7dp"
            android:textSize="14sp" />

        <EditText
            android:id="@+id/input_country"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:ems="10"
            android:hint="Country"
            android:inputType="textCapWords"
            android:padding="7dp"
            android:textSize="14sp" />

        <EditText
            android:id="@+id/input_state_province"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:ems="10"
            android:hint="State/Province/Region"
            android:inputType="textCapWords"
            android:padding="7dp"
            android:textSize="14sp" />

        <EditText
            android:id="@+id/input_city"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:ems="10"
            android:hint="City"
            android:inputType="textCapWords"
            android:padding="7dp"
            android:textSize="14sp" />
        <EditText
            android:id="@+id/input_email"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:ems="10"
            android:hint="Your Contact Email"
            android:inputType="textEmailAddress"
            android:padding="7dp"
            android:textSize="14sp" />

        <Button
            android:id="@+id/btn_post"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="20dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="50dp"
            android:background="@color/colorPrimary"
            android:text="Post"
            android:textColor="@android:color/white" />

        <ProgressBar
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:id="@+id/progressBar"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="120dp"
            android:visibility="invisible"/>

    </LinearLayout>


 </ScrollView>

 </FrameLayout>

Файл моего поста:

private void init(){

    mSelectImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: opening dialog to choose new photo");
            SelectPhotoDialog dialog = new SelectPhotoDialog();
            dialog.show(getFragmentManager(), getString(R.string.dialog_select_photo));
            dialog.setTargetFragment(PostFragment.this, 1);
        }
    });

    mSelectImage1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: opening dialog to choose new photo");
            SelectPhotoDialog dialog1 = new SelectPhotoDialog();
            dialog1.show(getFragmentManager(), getString(R.string.dialog_select_photo1));
            dialog1.setTargetFragment(PostFragment.this, 2);
        }
    });

Файл SelectPhotoDialog:

 @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_selectphoto, container, false);

    TextView selectPhoto = (TextView) view.findViewById(R.id.dialogChoosePhoto);
    selectPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: accessing phones memory.");
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, PICKFILE_REQUEST_CODE);

        }
    });

    TextView selectPhoto1 = (TextView) view.findViewById(R.id.dialogChoosePhoto1);

    selectPhoto1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: accessing phones memory.");
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, PICKFILE_REQUEST_CODE1);
        }
    });

    TextView takePhoto = (TextView) view.findViewById(R.id.dialogOpenCamera);
    takePhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: starting camera.");
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_REQUEST_CODE);

        }
    });
    return view;
}

Полный файл PostFragment:

https://pastebin.com/PJXB3cq1

Complete SelectPhotoDialog

https://pastebin.com/fF2Jj986

Файл IniversalImageLoader

Универсальный загрузчик изображений

1 Ответ

0 голосов
/ 18 ноября 2018

Я не уверен, но я не думаю, что есть достаточно информации ... я не могу найти UniversalImageLoader, на который ссылаются, я думаю, что он обрабатывает фактическую настройку изображения, как setImage подразумевает.

@Override

    public void getImagePath(Uri imagePath) {

        Log.d(TAG, "getImagePath: setting the image to imageview");

       // THIS LINE  UniversalImageLoader.setImage(imagePath.toString(), mSelectImage);

 

        //assign to global variable

        mSelectedBitmap = null;

        mSelectedUri = imagePath;

    }

Обновление до ответа
Итак, вот как я обычно выполняю диалог, который вы используете

private static final int READ_REQUEST_CODE = 42;

public void performFileSearch()
{

    // ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
    // browser.
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

    // Filter to only show results that can be "opened", such as a
    // file (as opposed to a list of contacts or timezones)
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    // Filter to show only images, using the image MIME data type.
    // If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
    // To search for all documents available via installed storage providers,
    // it would be "*/*".
    intent.setType("*/*");

    startActivityForResult(intent, READ_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode,
                             Intent resultData)
{
   if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK)
    {
       Uri uri = null;
        if (resultData != null)
        {
            uri = resultData.getData();
            String back = uri.toString();
           // DO SOMETHING WITH STRING
        }
    }
}

ТАК, КОГДА ВАШ КОД БЫЛ

    @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dialog_selectphoto, container, false);

    TextView selectPhoto = (TextView) view.findViewById(R.id.dialogChoosePhoto);
    selectPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: accessing phones memory.");
            performFileSearch()
        }
    });

    TextView selectPhoto1 = (TextView) view.findViewById(R.id.dialogChoosePhoto1);

    selectPhoto1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: accessing phones memory.");
            performFileSearch();
        }
    });

    TextView takePhoto = (TextView) view.findViewById(R.id.dialogOpenCamera);
    takePhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: starting camera.");
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_REQUEST_CODE);

        }
    });
    return view;
}

// Я не думаю, что это является причиной, просто потому, что все, кажется, течет, пока часть, которая устанавливает изображение ... Диалог вернет URI к изображению, но другой код устанавливает изображение не в том месте,

ImageView X = (ImageView) findViewById(R.id.ImageViewID); 
X.setBackgroundResource ?

Или что-то подобное, это то, что я ищу, я думаю, что это может быть причиной проблемы.

Поцарапайте это
Я нашел ImageLoader, и все, кажется, в порядке ..

Constructor Detail:

ImageLoader

public ImageLoader(RequestQueue queue, ImageLoader.ImageCache imageCache)Constructs a new ImageLoader.

// Parameters:queue - The RequestQueue to use for making image requests.imageCache - The cache to use as an L1 cache.

Вы пробовали другую форму настройки изображения?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...