How to display an image on the screen

Asked

Viewed 6,396 times

6

I’m doubtful to display an image on the screen on android. example. to call a sound use the following code:

Button button1;
MediaPlyer mp;
    button1 = (Button)findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {


        mp = MediaPlayer.create(Teste.this, R.raw.som);
        mp.start();

        }

    });

and how to call an image?

  • What is the image? Where is it?

  • I am making a code where you click on the image and it grows by taking the screen of the device and when you click again it decreases.

  • I’m done, Rodolfo, you want?

  • Where will these images be? In an app folder?

3 answers

5


In the Layout of your Activity must declare a ImageView

If you want it to be only visible after pressing a button you should include the attribute android:visibility="invisible"

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/imageView1"
    android:visibility="invisible"
    android:src="@drawable/nomeDaSuaImagem" />  

In the code of Activity, in the onClick button, make it visible:

Button button1;
ImageView imageView1;

imageView1 = (ImageView)findViewById(R.id.imageView1);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        imageView1.setVisibility(View.VISIBLE;
    }

});
  • valeu ramaral I’ll try it soon comment.

  • ramaral has to let imageView behind the buttons and when it opens grab the whole screen?

  • Edit your question and post the xml of his Activity

4

If you want to open the image in the default image viewer, you can do:

public void openInGallery(String imageId) {
   Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(imageId).build();
   Intent intent = new Intent(Intent.ACTION_VIEW, uri);
   startActivity(intent);
}

You can also try:

public void openImage(String imagePath) {
   Intent intent = new Intent();
   intent.setAction(Intent.ACTION_VIEW);
   intent.setDataAndType(Uri.parse("file://" + imagePath), "image/*");
   startActivity(intent);
}

Source

EXTERNAL_CONTENT_URI is used to specify an external location, if the image is in an internal location use INTERNAL_CONTENT_URI.

  • You know the right way to call the image path?

2

Your question was as much as complex and at the same time without goals for the goal:screen image on android. Well... Let’s get out of the critics and go for my answer.

Suposição e lógica:

Imagining that you want the customer to download a particular image, when starting the app, and, that it gets saved inside the images folder of your own device. What’s the point? I don’t know... What’s new about something? Then it would be necessary to download the image of a url externa and convert it to bitmap and thus display in a ImageView And ALSO, by clicking on it, it would be good to create a kind of lightbox so that it does not occupy so much space on the device screen with a fixed size, set. With all this, it would be easy to update all clients, with only one image, coming from an external server, because you could change it whenever you wanted, otherwise it would be inside drawble.

1.MainActivity. class

package app.test;

import java.io.File;

import android.app.Activity;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnTouchListener{

    //ISTO DETERMINA O TAMANHO DA IMAGEM DEPOIS DO TOQUE
    private float mScaleFactor = 6f;

    private float globalX;
    private Matrix mMatrix = new Matrix();    
    private float mFocusX = 0.f;
    private float mFocusY = 0.f;  
    private int mImageHeight = 0;
    private Uri caminho;
    ImageLoader imageLoader = new ImageLoader();


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

        //Isto esconde o erro na hora de baixar o bitmap para as versões mais atuais do SDK
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


       //Criando a novos diretórios somente INSTALAR O APP
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                     File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"/MeuApp/Imagens/");
                        directory.mkdirs();

                }

       //Obtendo DisplayMetrics do dispositivo: largura e altura.
       DisplayMetrics displayMetrics = getBaseContext().getResources().getDisplayMetrics();
       int width = displayMetrics.widthPixels;
       int height = displayMetrics.heightPixels;

        //Altere o valor atual: 10f, para um valor que desejar. Isto posicionará a imagem
        mFocusX = width/10f;
        mFocusY = height/10f;       

        ImageView view = (ImageView) findViewById(R.id.ImageView);

        //**2 passos para baixar a imagem, por isso os códigos devem está nessa ordem

        // 1 - Toda vez que o app for iniciado, ele ira baixar a imagem. Esta linha de código pode está onde desejar
        imageLoader.baixando(); 

        // 2 - Caminho da imagem baixada
        caminho = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/MeuApp/Imagens/" + "imagem" );

        view.setImageURI(caminho);  

        // Setando esta classe em touchListener para a ImageView
        view.setOnTouchListener(this);


    }



    @Override
    public boolean onTouch(View v, MotionEvent event) {

        //Se a posição 'x', no plano cartesiano, for menor que 102.4
        if (globalX < 102.4){

            //Setando uma nova escala para x e y, no plano 
            float scaledImageCenterX = (mImageHeight*mScaleFactor)/2;
            float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;       

            //Mudando escala
            mMatrix.postScale(mScaleFactor, mScaleFactor);
            //Mudando a transação
            mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);

            //Setando as novas configurações da ImageView
            ImageView view = (ImageView) v;
            view.setImageMatrix(mMatrix);           

            //Salvando valor da posição x na variável globalX através do Matrix
            float[] values = new float[9];
            mMatrix.getValues(values);
            globalX = values[Matrix.MTRANS_X];

            return false; 

        }else{  

             // AQUI ACONTECE A REVERSÃO DO TAMANHO ATRAVÉS DA FUNÇÃO reset();
             mMatrix.reset();

             //Setando as novas configurações da ImageView
             ImageView view = (ImageView) v;
             view.setImageMatrix(mMatrix);

             // zerando a posição x para a condicional ser refeita
             globalX = 0; 


        }
        return false;


    }   


}

2.ImageLoader. class

package app.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;


public class ImageLoader {

    //Conexão, baixando e convertendo

    public Bitmap getBitmapFromURL(String url) {
        try {
            URL src = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) src.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    //Salvando o Bitmap na pasta do app
    public void salvando(Bitmap abmp){      
        String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/MeuApp/Imagens/";
                File dir = new File(file_path);
                if(!dir.exists())
                dir.mkdirs();
                File file = new File(dir, "imagem");
                FileOutputStream fOut;
                try {
                fOut = new FileOutputStream(file);
                ;
                abmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
                fOut.flush();
                fOut.close();

                } catch (Exception e) {
                e.printStackTrace();
                }


    }

    //Executando os métodos: salvando e getBitmapFromURL
    public void baixando() {

        salvando(getBitmapFromURL("http://www.meusite.net/imagens/MATENHAesteTITULO.jpg"));

        return;
    } 

}

3.activity_main. xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="app.test.MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toque na Imagem" />

        <ImageView
            android:id="@+id/ImageView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView1"
            android:scaleType="matrix"
            android:src="@drawable/ic_launcher" />

</RelativeLayout>

Don’t forget to add this to Androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

DOUBTS? Leave a comment!

  • @Rodolfo, you still have problems?

  • Like, I play, the image grows and I play again and the image grows a little bit more and the third time it’s normal?

  • You moved it. Now you have to reconfigure.

  • Pay attention: Your image already comes big, it comes from the size that is in the external url folder ok? When you play it, it decreases, because the current setting sends it to a smaller scale than the current one (size). Can you understand? You have to decide how big your image will be, ON THE EXTERNAL SERVER, then change the settings in the code. Send me the salvando(getBitmapFromURL("...");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.