【问题标题】:how to build intent in activity and receive from fragment如何在活动中建立意图并从片段中接收
【发布时间】:2013-04-10 14:40:17
【问题描述】:

我是 Android 新手。我想做的是愚蠢的吗? 我在一个活动(EditPhoto)中建立了一个意图,如下所示:

            //Defining intent for loading image to the edit page
            Intent recentPhoto = new Intent(this, ImportPhoto.class);

            //Defining byte stream of image chosen
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 50, bs);

            //Transforming image to EditPhoto class in byte stream
            recentPhoto.putExtra("byteArray", bs.toByteArray());

            //Starting the intent
            startActivity(recentPhoto);

我正在尝试从另一个活动(ImportPhoto)的片段(FirstFragment)接收它,如下所示:

                // Getting the image back imported from EditPhoto page
                final Bitmap photo = BitmapFactory.decodeByteArray(getIntent().  
                                     getByteArrayExtra("byteArray"),
                         0,getIntent().getByteArrayExtra("byteArray").length);

        //Displaying the image in the image viewer
        viewGalleryImages.setImageBitmap(photo);

由于片段类是静态的,它说“无法从类型 Activity 对非静态方法 getIntent() 进行静态引用”。

我尝试使用捆绑包并将参数设置为片段,但又遇到了同样的问题。

另外,我尝试过 getActivity().getIntent.... 并且还像这样 ((ImportPhoto)getActivity()).getIntent 进行了 getActivity 转换...

我们将不胜感激任何形式的帮助。 提前致谢。

【问题讨论】:

    标签: android android-intent


    【解决方案1】:

    您正在解决这个错误,您没有将意图发送到片段。

    当你创建片段时,你会做这样的事情

    Fragment fragment = new FirstFragment();
    fragTransaction.add(fragment,null).commit;
    

    当您创建片段时,通过像这样将类转换为片段来创建扩展片段的类的实例

    FirstFragment first = (FirstFragment)fragment;
    

    然后在您的 FirstFragment 类中创建一个方法来获取照片或使用您刚刚创建的 first 值访问它的任何广告

    first.setPhoto(image);
    

    任何时候你需要一个片段来与一个活动通信,你需要创建一个从片段中读取的活动回调here

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 2021-03-03
      • 2016-03-08
      • 2014-04-27
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多