how to call an on-screen image on android

5

I have a question about displaying an image on the screen in android. example. to call a sound it uses 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 do you call an image?

    
asked by anonymous 25.01.2015 / 22:11

3 answers

4

Layou t of your Activity must declare a ImageView

If you want it to be visible only after pressing a button you should include the 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 Activity code, on the% button of the 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;
    }

});
    
25.01.2015 / 22:44
4

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

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);
}

Font

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

25.01.2015 / 22:25
2

Your question was both complex and at the same time without goals for the goal: screen image on android. Well ... Let's get out of the criticism and leave for my answer.

Suposição e lógica :

Wondering that you want the client to download a certain image when launching the app, and that it is saved inside the images folder of your own device. Why? I do not 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, when clicking on it, it would be nice to create a lightbox kind of thing so that it does not occupy as much space in screen of the device with a fixed size, set. With all this, it would be easy to update all clients, with a single image, coming from an external server, because you could change it whenever you wanted, on the contrary would be if you were within 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>

Do not forget to add this in 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!

    
26.01.2015 / 04:03