【问题标题】:Passing text from Fragment to Fragment to Activity onto receiving bitmap in Android Studio将文本从 Fragment 传递到 Fragment 到 Activity 到在 Android Studio 中接收位图
【发布时间】:2016-01-08 11:13:21
【问题描述】:

我基本上有 2 个片段和 2 个活动。 Fragment1 具有将它们传递给 Fragment2 的输入文本。 Fragment2 有 Textviews,之前输入的文本将被填充。 Activity1 制作一张图片并发送给 Activity2。 Activity2 收到该图片并让您有机会添加在 Fragment2 中创建的文本。

现在我想将图片保存到我的 SD 卡或画廊,包括文本。我知道我必须将 Textviews 转换为位图,然后将它们与原始图片“合并”,但是如何处理 Fragment2 和 Activity2 之间的通信?

这是我的想法,但我一直在发送和接收短信:

public void setText(String top, String bottom){
    topText.setText(top);
    bottomText.setText(bottom);

    Bitmap topText = Bitmap.createBitmap(topText.getDrawingCache());
    Bitmap bottomText = Bitmap.createBitmap(bottomText.getDrawingCache());
}

这发生在 Fragment2 中。

imgTakenPhoto = (ImageView) findViewById(R.id.imgTakenPhoto);
    if(getIntent().hasExtra("byteArray")) {
        Bitmap b = BitmapFactory.decodeByteArray(
        getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
        imgTakenPhoto.setImageBitmap(b);
    }

这发生在Activity2(接收图片) 如果 Fragment2 是一个 Activity,我会像在 Activity1 中那样发送它,但这是一个 Fragment 让我感到困惑。 在我忘记之前:Fragment1 和 2 是 Activity2 的一部分。

谁能帮帮我?

最好的问候

【问题讨论】:

  • Fragment1Fragment2 是否附加到 Activity1Activity2 或其他?您可以通过 FragmentManager.findFragmentByTag()FragmentManager.findFragmentById() 方法从父 Activity 中检索它,具体取决于您将它们附加到 Activity 的方式
  • @NitroNbg 是的,Fragment1 和 Fragment2 都附加到 Activity2。这正是我所需要的,但我如何使用片段管理器接收位图?

标签: android android-fragments android-intent android-studio bitmap


【解决方案1】:

如果我理解正确,您应该可以在 Activity2 中使用它:

Fragment2 frag = (Fragment2) getFragmentManager().findFragmentById(R.id.frag2); //change the id with real id
String textInTextView1 = ((TextView)frag.getView().findViewById(R.id.textview1)).getText().toString();

对于所有附加到 Fragment2 根视图的 TextView 对象,依此类推。

【讨论】:

  • 这就是方法!最好还检查接收到的片段是否为空。根据访问片段的“位置”和“时间”,检查“frag.getView()”是否返回 null 是个好主意。但这在大多数情况下是不必要的。
【解决方案2】:

你可以像数据库一样将数据保存在应用程序的设置中,并在另一个片段中获取数据。 你可以在Saving Key-Value Sets查看更多内容

要写入数据:

SharedPreferences sharedPref = 
getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

要检索它:

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
    getString(R.string.preference_file_key), Context.MODE_PRIVATE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2013-07-26
    相关资源
    最近更新 更多