如何在Bundle帮助下使用Key传递ImageView

时间:2018-01-26 21:35:06

标签: java android android-imageview

我使用Firebase检索实时数据。我想使用bundle显示图像,标题和描述。所以这是我的代码。标题和说明以良好的方式反映,但图像未加载到设备上。我该如何解决这个问题?

package com.mypackage.cardstack.fragment;

import android.media.Image;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.mypackage.cardstack.R;

public class CardStackFragment extends Fragment {


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView =  inflater.inflate(R.layout.fragment_card, container, false);
        final Bundle bundle = getArguments();
        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("TGA", "Clikced on " + bundle.getString("TITLE"));

            }
        });
        TextView t = (TextView) rootView.findViewById(R.id.text1);
        TextView d = (TextView) rootView.findViewById(R.id.desc1);
        ImageView m=(ImageView) rootView.findViewById(R.id.fish);

        t.setText(bundle.getString("TITLE"));
        d.setText(bundle.getString("DESC"));
        m.setImageResource(bundle.getInt("IMAGE"));


        return rootView;
    }

    public static CardStackFragment getFragment(String title, String desc,String image) {
        CardStackFragment cardStackFragment = new CardStackFragment();
        Bundle args = new Bundle();
        args.putString("TITLE", title);
        args.putString("DESC", desc);
        args.putString("IMAGE",image);
        cardStackFragment.setArguments(args);
        return cardStackFragment;
    }
}

2 个答案:

答案 0 :(得分:1)

我认为问题在于您将Image Source作为String放入Bundle,然后将其作为Int读取....我认为您要保存Image资源ID(R.drawable.yourImage) ,例如)进入捆绑。这是一个整数。你应该能够getInt()来检索它。

答案 1 :(得分:0)

将下载的图像转换为字节数组并将其发送到主活动

  Bundle bundle = new Bundle();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    if(bitmap!=null) {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();  
        bundle.putByteArray("your key string", byteArray);

}

同样在主要活动中将其检索为

 byte[] data= message.getData().getByteArray(key);                                               
 Bitmap bmp= BitmapFactory.decodeByteArray(data,0,data.length);
                    imageView= findViewById(R.id.largeImage);
                    imageView.setVisibility(View.VISIBLE);
                    imageView.setImageBitmap(bmp);

另外,请确保在主要活动中将图片视图显示为可见。