访问AlertDialog中的视图,来自于正在膨胀的活动

huangapple 未分类评论47阅读模式
英文:

Access a view within an AlertDialog from the inflating activity

问题

Activity.Java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri selectedImageUri = null;
    Uri selectedImage;
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK) {
        filePathPicTemp = Environment.getExternalStorageDirectory() + Variables.tempsPictures + "foto.jpg";
        Bitmap bMap = BitmapFactory.decodeFile(filePathPicTemp);
        bMap = resizeImage(getApplicationContext(), bMap, 640, 480);
        ((ImageView) findViewById(R.id.ivModalComment)).setImageBitmap(bMap);
        try {
            FileOutputStream out = new FileOutputStream(filePathPicTemp);
            bMap.compress(Bitmap.CompressFormat.PNG, 50, out);
            out.flush();
            out.close();
            imageComment = new File(filePathPicTemp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

GenericMethods.Java

public static void addCommentDialog(final String idRoute, File imageComment, AppCompatActivity mContext, ViewGroup viewGroup) {
    View dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment, mContext.findViewById(android.R.id.content), false);
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setView(dialogView);
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
    UserSessionManager userSessionManager = new UserSessionManager(mContext);
    Button btnExitComments = dialogView.findViewById(R.id.btnExitComments);
    Button btnUploadPhoto = dialogView.findViewById(R.id.btnUploadPhoto);
    Button btnTakePic = dialogView.findViewById(R.id.btnTakePic);
    Button btnSendComment = dialogView.findViewById(R.id.btnSendComment);
    CircleImageView cvUserIcon = dialogView.findViewById(R.id.cvUserIcon);
    ImageView ivModalComment = dialogView.findViewById(R.id.ivModalComment);
    final EditText taComment = dialogView.findViewById(R.id.taComment);
    final RatingBar rbComment = dialogView.findViewById(R.id.rbComment);

    Glide.with(mContext)
        .load(Variables.URL_GENERAL + "fotos_usuarios/" + userSessionManager.getUrlperfilImage())
        .diskCacheStrategy(DiskCacheStrategy.NONE)
        .error(R.drawable.user_icon)
        .into(cvUserIcon);

    btnExitComments.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.hide();
        }
    });

    btnUploadPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            mContext.startActivityForResult(Intent.createChooser(intent, "Seleccione una imagen"), 2);
        }
    });

    btnTakePic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) !=
                        PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(mContext,
                            Manifest.permission.CAMERA)) {
                    } else {
                        ActivityCompat.requestPermissions(mContext, new String[]
                                {Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMARA);
                    }
                } else {
                    abrirCamara(mContext);
                }
            } else {
                abrirCamara(mContext);
            }
        }
    });

    btnSendComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            UserSessionManager userSessionManager = new UserSessionManager(mContext);
            sendComment(idRoute, imageComment, taComment.getText().toString(),
                    userSessionManager.getIdUser(), rbComment.getRating(), alertDialog, 0, mContext);
        }
    });
}

XML file that is inflated in method:

<ScrollView
    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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

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

        <!-- Other XML content, not translated here -->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/common_google_signin_btn_text_dark_disabled"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btnUploadPhoto"
                style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                app:icon="@drawable/ic_file_atach"
                android:layout_weight="1"
                app:iconGravity="textEnd" />

            <Button
                android:id="@+id/btnTakePic"
                style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                app:icon="@drawable/ic_menu_camera"
                app:iconGravity="textEnd" />

            <ImageView
                android:id="@+id/ivModalComment"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1" />

            <Button
                android:id="@+id/btnSendComment"
                style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center|end"
                android:layout_weight="10"
                android:gravity="center|end"
                android:text="Enviar"
                app:icon="@drawable/ic_menu_send"
                app:iconGravity="end" />

        </LinearLayout>
    </LinearLayout>
</ScrollView>
英文:

I am trying to access an ImageView inside an AlertDialog but I get NullPointerException when I try to put an image to it

I try to access from onActivityResult in the activity that invokes the method. But this gives me error. And the datelle that I can only do it from onActivityResult since I must wait for the image of the activity of the camera

This is my code:

Activity.Java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri selectedImageUri = null;
    Uri selectedImage;
    //Comprobamos que la foto se a realizado
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 &amp;&amp; resultCode == RESULT_OK) {
        //Creamos un bitmap con la imagen recientemente
        //almacenada en la memoria
        filePathPicTemp = 
        Environment.getExternalStorageDirectory()+Variables.tempsPictures+&quot;foto.jpg&quot;;
        Bitmap bMap = BitmapFactory.decodeFile(filePathPicTemp);
        //A&#241;adimos el bitmap al imageView para
        //mostrarlo por pantalla
        bMap = resizeImage(getApplicationContext(),bMap,640,480);

        ((ImageView) findViewById(R.id.ivModalComment)).setImageBitmap(bMap);
       // bMap = BitmapFactory.decodeResource(getResources(),ivModalComment.getId());
        try { // Try to Save #2
            FileOutputStream out = new FileOutputStream(filePathPicTemp);
            bMap.compress(Bitmap.CompressFormat.PNG, 50, out);
            out.flush();
            out.close();
            imageComment = new File(filePathPicTemp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

GenericMethods.Java (This is used to repeated functions)

public static void addCommentDialog(final String idRoute, File imageComment, AppCompatActivity 
    mContext, ViewGroup viewGroup) {
    //Se infla la vista
    View dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_comment, 
        mContext.findViewById(android.R.id.content), false);

    //Se instancia el builder
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

    //Se asigna el dialogo al builder
    builder.setView(dialogView);

    //Se crea y se muestra la alerta
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();
    UserSessionManager userSessionManager = new UserSessionManager(mContext);
    Button btnExitComments = dialogView.findViewById(R.id.btnExitComments);
    Button btnUploadPhoto = dialogView.findViewById(R.id.btnUploadPhoto);
    Button btnTakePic = dialogView.findViewById(R.id.btnTakePic);
    Button btnSendComment= dialogView.findViewById(R.id.btnSendComment);
    CircleImageView cvUserIcon= dialogView.findViewById(R.id.cvUserIcon);

    ImageView ivModalComment  =  dialogView.findViewById(R.id.ivModalComment);

    final EditText taComment = dialogView.findViewById(R.id.taComment);
    final RatingBar rbComment  = dialogView.findViewById(R.id.rbComment);

    Glide.with(mContext)
    .load(Variables.URL_GENERAL+&quot;fotos_usuarios/&quot;+userSessionManager.getUrlperfilImage())
            .diskCacheStrategy(DiskCacheStrategy.NONE)
    .error(R.drawable.user_icon).into(cvUserIcon);

    //Boton de salir
    btnExitComments.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            alertDialog.hide();
        }
    });

    //Boton para acceder a la galeria y obtener una imagen
    btnUploadPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType(&quot;image/*&quot;);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            mContext.startActivityForResult(Intent.createChooser(intent, &quot;Seleccione una imagen&quot;),2);
        }
    });

    //Boton para abrir la camara y tomar la foto
    btnTakePic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (Build.VERSION.SDK_INT&gt;Build.VERSION_CODES.LOLLIPOP_MR1) {// Marshmallow+
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA)!= 
                    PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(mContext, 
                        Manifest.permission.CAMERA)) {
                        // Show an expanation to the user *asynchronously* -- don&#39;t block
                        // this thread waiting for the user&#39;s response! After the user
                        // sees the explanation, try again to request the permission.
                    } else {
                        ActivityCompat.requestPermissions(mContext, new String[] 
                        {Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMARA);
                        // MY_PERMISSIONS_REQUEST_CAMARA es una constante definida en la app. El 
                        m&#233;todo callback obtiene el resultado de la petici&#243;n.
                    }
                }else{ //have permissions
                    abrirCamara(mContext);
                }
            }else{ // Pre-Marshmallow
                abrirCamara (mContext);
            }
        }
    });

    //Boton de enviar comentario
    btnSendComment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            UserSessionManager userSessionManager = new UserSessionManager(mContext);
            //progressDialog.show();
            sendComment(idRoute, imageComment, taComment.getText().toString(), 
            userSessionManager.getIdUser(), rbComment.getRating(), alertDialog, 0, mContext);
        }
    });
}

XML file that is inflated in method:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;ScrollView
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:orientation=&quot;vertical&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
&gt;

&lt;LinearLayout
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:orientation=&quot;vertical&quot;&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;horizontal&quot;
        android:padding=&quot;18dp&quot;&gt;
        &lt;de.hdodenhof.circleimageview.CircleImageView
            android:layout_width=&quot;70dp&quot;
            android:layout_height=&quot;70dp&quot;
            android:src=&quot;@drawable/user_icon&quot;
            android:id=&quot;@+id/cvUserIcon&quot;/&gt;
        &lt;LinearLayout
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;match_parent&quot;
            android:orientation=&quot;horizontal&quot;&gt;

            &lt;LinearLayout
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;match_parent&quot;
                android:layout_marginLeft=&quot;10dp&quot;
                android:layout_weight=&quot;1&quot;
                android:gravity=&quot;center&quot;
                android:orientation=&quot;vertical&quot;&gt;

                &lt;TextView
                    android:id=&quot;@+id/textView15&quot;
                    android:layout_width=&quot;match_parent&quot;
                    android:layout_height=&quot;wrap_content&quot;
                    android:text=&quot;Usuario&quot; /&gt;

                &lt;TextView
                    android:id=&quot;@+id/textView19&quot;
                    android:layout_width=&quot;match_parent&quot;
                    android:layout_height=&quot;wrap_content&quot;
                    android:text=&quot;Tu comentario sera publico, por favor lee nuestras normas de 
                                     comunidad aqui&quot;
                    android:textSize=&quot;10sp&quot; /&gt;

            &lt;/LinearLayout&gt;


            &lt;Button
                android:id=&quot;@+id/btnExitComments&quot;
                style=&quot;@style/Widget.MaterialComponents.Button.TextButton.Icon&quot;
                android:layout_width=&quot;50dp&quot;
                android:layout_height=&quot;50dp&quot;
                android:layout_gravity=&quot;center|end&quot;

                app:icon=&quot;@drawable/ic_back_arrow_black&quot;
                app:iconGravity=&quot;textStart&quot;
                app:iconPadding=&quot;0dp&quot; /&gt;

        &lt;/LinearLayout&gt;

    &lt;/LinearLayout&gt;
    &lt;RatingBar
        android:id=&quot;@+id/rbComment&quot;
        style=&quot;@android:style/Widget.Material.Light.RatingBar.Indicator&quot;
        android:isIndicator=&quot;false&quot;
        android:clickable=&quot;true&quot;
        android:focusable=&quot;true&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;30dp&quot;
        android:layout_gravity=&quot;center&quot;
        android:layout_weight=&quot;1&quot;
        android:numStars=&quot;5&quot;
        android:stepSize=&quot;0.5&quot;/&gt;
    &lt;com.google.android.material.textfield.TextInputLayout
        android:layout_margin=&quot;6dp&quot;
        android:id=&quot;@+id/outlinedTextField&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:hint=&quot;Puntue y escriba un comentario&quot;
        style=&quot;@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox&quot;&gt;



        &lt;com.google.android.material.textfield.TextInputEditText
            android:id=&quot;@+id/taComment&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;300dp&quot;
            android:inputType=&quot;textMultiLine&quot;
            android:ems=&quot;10&quot;
            /&gt;


    &lt;/com.google.android.material.textfield.TextInputLayout&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:background=&quot;@color/common_google_signin_btn_text_dark_disabled&quot;
        android:orientation=&quot;horizontal&quot;&gt;

        &lt;Button
            android:id=&quot;@+id/btnUploadPhoto&quot;
            style=&quot;@style/Widget.MaterialComponents.Button.TextButton.Icon&quot;
            android:layout_width=&quot;40dp&quot;
            android:layout_height=&quot;wrap_content&quot;
            app:icon=&quot;@drawable/ic_file_atach&quot;
            android:layout_weight=&quot;1&quot;
            app:iconGravity=&quot;textEnd&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/btnTakePic&quot;
            style=&quot;@style/Widget.MaterialComponents.Button.TextButton.Icon&quot;
            android:layout_width=&quot;40dp&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_weight=&quot;1&quot;
            app:icon=&quot;@drawable/ic_menu_camera&quot;
            app:iconGravity=&quot;textEnd&quot; /&gt;
        &lt;ImageView
            android:id=&quot;@+id/ivModalComment&quot;
            android:layout_width=&quot;50dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            /&gt;

        &lt;Button
            android:id=&quot;@+id/btnSendComment&quot;
            style=&quot;@style/Widget.MaterialComponents.Button.TextButton.Icon&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_gravity=&quot;center|end&quot;
            android:layout_weight=&quot;10&quot;
            android:gravity=&quot;center|end&quot;

            android:text=&quot;Enviar&quot;
            app:icon=&quot;@drawable/ic_menu_send&quot;
            app:iconGravity=&quot;end&quot; /&gt;
    &lt;/LinearLayout&gt;
&lt;/LinearLayout&gt;
&lt;/ScrollView&gt;

答案1

得分: 0

你试过这个吗

        AlertDialog.Builder builder= new AlertDialog.Builder(this);
        LayoutInflater inflater= getLayoutInflater();
        final View myView= inflater.inflate(R.layout.alert_dialog_text_entry, null);
        builder.setTitle("关于");
        builder.setMessage("测试");
        builder.setView(myView);
        AlertDialog alert= builder.create();
        TextView stateful= (TextView)myView.findViewById(R.id.TextView01);
        stateful.setText("更多测试");
        Log.d(Utilities.TAG,stateful.toString());
        alert.show();

你可以使用 `myView.findViewById()` 来获取你想要的任何组件的视图尝试一下我相信它会对你有用
英文:

Have you tried this?

    AlertDialog.Builder builder= new AlertDialog.Builder(this);
    LayoutInflater inflater= getLayoutInflater();
    final View myView= inflater.inflate(R.layout.alert_dialog_text_entry, null);
    builder.setTitle(&quot;About&quot;);
    builder.setMessage(&quot;Test&quot;);
    builder.setView(myView);
    AlertDialog alert= builder.create();
    TextView stateful= (TextView)myView.findViewById(R.id.TextView01);
    stateful.setText(&quot;More Testing&quot;);
    Log.d(Utilities.TAG,stateful.toString());
    alert.show();

You can use myView.findViewById() to get the view of any component that you wish. Try it and I am sure that it will work for you.

huangapple
  • 本文由 发表于 2020年7月26日 15:10:34
  • 转载请务必保留本文链接:https://java.coder-hub.com/63097181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定