Страница 1 из 1

Как передать объект нажатой кнопки через onClickListener

Добавлено: 26 фев 2016, 12:52
Mamay
Как передать объект нажатой кнопки через onClickListener в метод?
Есть много viev элементов с одинаковыми кнопками ("загрузить и открыть") которые несут в себе разные url и отправляют через onClickListener url и content в отдельный клас с набором методов однин из которых загружает url . Задача после загрузки сменить надпись на кнопке с "загрузить и открыть" на "открыть" и сделать видимой кнопку "удалить", я реализовал данные функции сделав метод проверяющий наличие файла который срабатывает в onCreate, НО кнопки меняются только после перезагрузки активити, тоесть если я нажимаю "загрузить и открыть" файл загружается и открывается, но когда я его закрываю и возвращаюсь на список файлов загрузки, то там попрежнему написано "загрузить и открыть" и нет кнопки "удалить" , кнопки меняются только после перезагрузки приложения (активити).
ВОПРОС как передавать вместе с url через onClickListener (или подругому) объект кнопки которая была нажата и после отработки метода сразу поменять атрибуты кнопок ?
Спасибо

Re: Как передать объект нажатой кнопки через onClickListener

Добавлено: 26 фев 2016, 12:58
TimBrown
По идее кнопка имеет свой id известный Вам.

После отработки? В другом потоке надеюсь?

((Button) findViewById(R.id.айдикнопки)).setText("открыть");

А вообще дайте код, чтобы пальцем в небо не тыкать

Re: Как передать объект нажатой кнопки через onClickListener

Добавлено: 26 фев 2016, 14:46
Mamay
Потоки не использовал :oops: не проходил пока.
вот кнопки "загрузить и открыть" и "удалить"
и onClickListener передающий url

Код: Выделить всё

PDFTools pdfe = new PDFTools();

final Button bB8065 = (Button) findViewById(R.id.butA8065);
        bA8065.setOnClickListener(this);
final Button dB8065 = (Button) findViewById(R.id.dB8065);
        dB8065.setOnClickListener(this);

if (pdfe.downloadInspection(MainActivity.this,strB8065) || !pdfe.isPDFSupported(MainActivity.this)){
            bB8065.setText (R.string.open);
        }
        else {
            bB8065.setText(R.string.download);
        }

        if (pdfe.downloadInspection(MainActivity.this, strB8065)){
            dB8065.setVisibility(View.VISIBLE);
        } else {
            dB8065.setVisibility(View.GONE);
        }

 @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.butA8065:
                pdfe.showPDFUrl(this, strA8065        //Я ДУМАЛ ЗДЕСЬ ПЕРЕДАВАТЬ КНОПКУ В КЛАСС pdfe И ТАМ В МЕТОДЕ КОТОРЫЙ ОТВЕЧАЕТ ЗА ЗАГРУЗКУ МЕНЯТЬ АТРИБУТЫ КНОПКИ ПОСЛЕ ОТРАБОТКИ МЕТОДА );
                break;
            case R.id.dA8065:
                pdfe.deleteFile(this, strA8065);
                break;
}
}
Метод класса pdfe в который передаются параметры

Код: Выделить всё

 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile(tempFile) );
            return;
        }


        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show(context, context.getString(R.string.pdf_show_local_progress_title), context.getString(R.string.pdf_show_local_progress_content), true);

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }
                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );      // ВОТ ЗДЕСЬ ПОСЛЕ ЗАГРУЗКИ ПОЛУЧИТЬ НАЖАТУЮ КНОПКУ И СМЕНИТЬ ЕЕ АТРИБУТЫ buttonDownload.setText, buttonDelete.setVisibility
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }
Полный класс pdfe:

Код: Выделить всё

package com.mittereflores.bricktest1;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;



/**
 * Created by Оксана on 13.02.2015.
 */
public class PDFTools {
    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";
    private static final int a = 0;
    private static final int b = 1;



    /**
     * If a PDF reader is installed, download the PDF file and open it in a reader.
     * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.<br />
     * <br />
     * <b>BEWARE:</b> This method
     * @param context
     * @param pdfUrl
     * @return
     */
    public static void showPDFUrl( final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
                if(isNetworkStatusAvialable ( context )) {
                    downloadAndOpenPDF(context, pdfUrl);
                } else {
                    Toast toast = Toast.makeText(context.getApplicationContext(), context.getString(R.string.noInternet), Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.TOP, 0, 0);
                    toast.show();
                    opendPDF(context, pdfUrl);
                }

            } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void opendPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring(pdfUrl.lastIndexOf("/") + 1);
        // The place where the downloaded PDF file will be put
        final File tempFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename);
        if (tempFile.exists()) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF(context, Uri.fromFile(tempFile));
            return;
        }
    }

    /**
     * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
     * @param context
     * @param pdfUrl
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile(tempFile) );
            return;
        }


        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show(context, context.getString(R.string.pdf_show_local_progress_title), context.getString(R.string.pdf_show_local_progress_content), true);

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }
                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    /**
     * Show a dialog asking the user if he wants to open the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
                .setTitle( R.string.pdf_show_online_dialog_title )
                .setMessage( R.string.pdf_show_online_dialog_question )
                .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
                .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        openPDFThroughGoogleDrive(context, pdfUrl);
                    }
                })
                .show();
    }

    /**
     * Launches a browser to view the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity(i);
    }
    /**
     * Open a local PDF file with an installed reader
     * @param context
     * @param localUri
     */
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Checks if any apps are installed that supports reading of PDF files.
     * @param context
     * @return
     */
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType(Uri.fromFile(tempFile), PDF_MIME_TYPE);
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

    public static boolean isNetworkStatusAvialable (Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null)
        {
            NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
            if(netInfos != null)
                if(netInfos.isConnected())
                    return true;
        }
        return false;
    }



    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static int downloadPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile(tempFile) );
            return a;
        }

        // Show progress dialog while downloading
//        final ProgressDialog progress = ProgressDialog.show(context, context.getString(R.string.pdf_show_local_progress_title), context.getString(R.string.pdf_show_local_progress_content), true);

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                if ( !progress.isShowing() ) {
//                    return;
//                }
                context.unregisterReceiver( this );

//                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
//                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue(r);
        return b;
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static boolean downloadInspection(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring(pdfUrl.lastIndexOf("/") + 1);
        // The place where the downloaded PDF file will be put
        final File tempFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename);
        if (tempFile.exists()) {
            // If we have downloaded the file before, just go ahead and show it.
            return true;
        }
        return false;
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void deleteFile (final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring(pdfUrl.lastIndexOf("/") + 1);
        // The place where the downloaded PDF file will be put
        final File tempFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename);
        if (tempFile.exists()) {
            // If we have downloaded the file before, just go ahead and show it.
            tempFile.delete();
            Toast toast = Toast.makeText(context.getApplicationContext(), context.getString(R.string.fileDeleted), Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP, 0, 0);
            toast.show();
            opendPDF(context, pdfUrl);
        }
        return;
    }

}

Может я иду в неправильном направлении и это нужно сделать подругому?
Зачем здесь применять многопоточность?