将文本从Fragment传递到Fragment到Activity,在Android Studio

时间:2016-01-08 11:13:21

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

我基本上有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中所做的那样,但这是一种让我困惑的片段。 在我忘记之前:Fragment1和2是Activity2的一部分。

任何人都可以帮助我吗?

祝你好运

2 个答案:

答案 0 :(得分: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();

对于附加到TextView根视图的所有Fragment2个对象,等等。

答案 1 :(得分:0)

Yo可以将数据保存在应用程序的设置中,就像数据库一样,在另一个片段中,您可以获得数据。 您可以在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);