Android Image Dialog / Popup - PullRequest
       25

Android Image Dialog / Popup

44 голосов
/ 08 октября 2011

Возможно ли иметь только всплывающее / всплывающее изображение в приложении Android?Это похоже на переопределение нормального вида AlertDialog, так что он содержит только изображение и ничего больше.

РЕШЕНИЕ: Я смог найти ответ благодаря помощи @ blessenm.Маскирование деятельности как диалога кажется идеальным способом.Ниже приведен код, который я использовал.Это диалоговое стилизованное действие может быть вызвано приложением так же, как и при запуске нового действия

ImageDialog.java

public class ImageDialog extends Activity {

    private ImageView mDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_dialog_layout);



        mDialog = (ImageView)findViewById(R.id.your_image);
        mDialog.setClickable(true);


        //finish the activity (dismiss the image dialog) if the user clicks 
        //anywhere on the image
        mDialog.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
        });

    }
}

your_dialog_layout.xml

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image_dialog_root" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:gravity = "center">

    <ImageView
        android:id="@+id/your_image"  
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src = "@drawable/your_image_drawable"/>

</FrameLayout>

Крайне важно, чтобы для этого действия был установлен следующий стиль:

styles.xml

  <style name="myDialogTheme" parent="@android:style/Theme.Dialog">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:background">@android:color/transparent</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:windowContentOverlay">@null</item>
   </style>

Последний шаг - объявить этот стиль для действия в манифесте следующим образом:

 <activity android:name=".ImageDialog" android:theme="@style/myDialogTheme" />

Ответы [ 7 ]

58 голосов
/ 25 июля 2014

Нет xml:

public void showImage() {
    Dialog builder = new Dialog(this);
    builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
    builder.getWindow().setBackgroundDrawable(
        new ColorDrawable(android.graphics.Color.TRANSPARENT));
    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialogInterface) {
            //nothing;
        }
    });

    ImageView imageView = new ImageView(this);
    imageView.setImageURI(imageUri);
    builder.addContentView(imageView, new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, 
            ViewGroup.LayoutParams.MATCH_PARENT));
    builder.show();
}
39 голосов
/ 08 октября 2011

Если вы просто хотите использовать обычный диалог, то что-то вроде этого должно работать

Dialog settingsDialog = new Dialog(this);
settingsDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
settingsDialog.setContentView(getLayoutInflater().inflate(R.layout.image_layout
        , null));
settingsDialog.show();

image_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:orientation="vertical">
    <ImageView android:layout_width="wrap_content" 
        android:layout_height="wrap_content" android:src="YOUR IMAGE"/>
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="OK" android:onClick="dismissListener"/>
</LinearLayout>
1 голос
/ 12 декабря 2018

Вы можете сделать это легко, создав фрагмент диалога в Kotlin:

BigImageDialog.kt

    class BigImageDialog():DialogFragment() {
    private var imageUrl = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            imageUrl = arguments.getString("url")
        }
    }
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val v = inflater!!.inflate(R.layout.dialog_big_image, container, false)
        this.dialog.window.requestFeature(Window.FEATURE_NO_TITLE)
        Picasso.get().load(imageUrl).into(v.bigImageView)
        return v
    }

    override fun onStart() {
        super.onStart()

        val dialog = dialog
        if (dialog != null) {
            dialog.window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(imageUrl: String) =
                BigImageDialog().apply {
                    arguments = Bundle().apply {
                        putString("url", imageUrl)
                    }
                }
    }
}

dialog_big_image.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">

    <ImageView
        android:id="@+id/bigImageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Диалог открытия:

"smallImageView".setOnClickListener { BigImageDialog.newInstance("image url").show(fragmentManager,"") }
1 голос
/ 13 октября 2017

Попробуйте следующее:
Также есть изображение zoom_in / zoom_out.

Шаг 1:
Добавьте compile 'com.github.chrisbanes.photoview:library:1.2.4' к вашему build.gradle
Шаг 2:
Добавьте следующий xml


custom_fullimage_dialoge.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root" android:orientation="horizontal"
              android:layout_width="fill_parent" android:layout_height="fill_parent"
              android:padding="10dp">
    <ImageView android:id="@+id/fullimage" android:layout_width="fill_parent"
               android:layout_height="fill_parent">
    </ImageView>

    <TextView android:id="@+id/custom_fullimage_placename"
              android:layout_width="wrap_content" android:layout_height="fill_parent"
              android:textColor="#FFF">
    </TextView>
</LinearLayout>

Шаг 3:

private void loadPhoto(ImageView imageView, int width, int height) {

    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    //dialog.setContentView(R.layout.custom_fullimage_dialog);
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.custom_fullimage_dialog,
            (ViewGroup) findViewById(R.id.layout_root));
    ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
    image.setImageDrawable(imageView.getDrawable());
    image.getLayoutParams().height = height;
    image.getLayoutParams().width = width;
    mAttacher = new PhotoViewAttacher(image);
    image.requestLayout();
    dialog.setContentView(layout);
    dialog.show();

}

Шаг 4:

user_Image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Display display = getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        loadPhoto(user_Image,width,height);
    }
});
1 голос
/ 11 января 2017

Без использования диалога вы можете использовать эту библиотеку, чтобы сделать изображение очень легко всплывающим.

https://github.com/chathuralakmal/AndroidImagePopup

1 голос
/ 08 октября 2011

Более гибкий и рекомендуемый способ - использовать DialogFragment.Если вы хотите поддерживать версии до 3.0, вы можете использовать библиотеку совместимости

1 голос
/ 08 октября 2011

Есть несколько способов сделать это. Но если вы хотите, чтобы ваше изображение показывалось выше существующего действия, вы можете использовать действие с android: theme = "@ style / Theme.Transparent", определенным в манифесте. Затем создайте макет так, чтобы единственный ImageView располагался в центре экрана. Пользователю придется нажать кнопку «назад», чтобы выйти из этого, но, похоже, это то, что вы хотите.

Если вы хотите, чтобы это выглядело как реальный диалог, вы всегда можете использовать диалоговое стилизованное действие, используя Theme.Dialog. ИЛИ, вы можете просто использовать диалог и настроить его.

...