1. 程式人生 > >Android Activity、Fragment之間的資料傳遞和返回

Android Activity、Fragment之間的資料傳遞和返回

Activity之間通過Intent傳遞資料

        Intent intent = new Intent(this, TwoActivity.class);
        intent.putExtra("key", "value");
        startActivity(intent);

像這樣直接通過Intent put就可以傳遞一些基本被型別的資料,並在第二個Activity中通過key去獲取相應的值

        getIntent().getStringExtra("key");

Bitmap類,實現了Parcelable藉口,所以如果想要傳遞Bitmap物件則可以直接傳遞過去

    public void onClick(View view) {
        Intent intent = new Intent(this, TwoActivity.class);
        intent.putExtra("key", "value");
        Bitmap bitmap = BitmapFactory.
                decodeResource(getResources(), R.mipmap.ic_launcher);
        intent.putExtra("bitmap", bitmap);
        startActivity(intent);
    }

在第二Activity中呼叫getParcelableExtra方法接收:

        ((ImageView) findViewById(R.id.image))
                .setImageBitmap((Bitmap) getIntent().getParcelableExtra("bitmap"));

如果想要傳遞實體類,則需要該實體類實現Serializable介面

package wkk.app6;

import java.io.Serializable;

/**
 * Created by wkk on 2016/7/19.
 */
public
class Test implements Serializable { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }

傳遞

        Test test=new Test();
        test.setMessage("123");
        intent.putExtra("test",test);
        startActivity(intent);

接收

        Intent intent = getIntent();
        Test test = (Test) intent.getSerializableExtra("test");

有時候我們需要在第二個Activity中做了一些操作後返回上一個Activity的時候將資料返回給上一個Activity,那麼我們就需要呼叫

startActivityForResult(intent,requestCode);

方法引數是Intent和requestCode

在第二個Activity中呼叫setResult方法返回:

    private static final int resultCode = 2;
    private void back() {
        setResult(resultCode, new Intent());
        finish();
    }

並且在第一個Activity中通過重寫onActivityResult方法接收資料:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 請求碼                          返回碼
        if(requestCode==this.requestCode&&resultCode==TwoActivity.resultCode){
            //data就是上一個Activity呼叫setResult方法時傳遞過來的Intent
            Toast.makeText(this,data.getStringExtra("a"),Toast.LENGTH_SHORT).show();
        }
    }

Activity向Fragment傳遞資料:
想要傳遞的資料可以放在bundle中

        FragmentA a = new FragmentA();
        Bundle bundle = new Bundle();
        a.setArguments(bundle);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.frameLayout, a).commit();

Fragment獲取傳遞過來的資料:

Bundle bundle = getArguments();

Fragment向Activity傳遞訊息有兩種方法
第一個是,通過getActivity()方法獲取到相應的Actvivity物件,然後呼叫Activity中的方法

        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.showToast("呵呵");

第二個就是通過介面回調了,在Fragment內寫一個介面讓Activity去實現,並在需要的時候呼叫,可以將資料以引數的形勢傳遞過去

package wkk.app5;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentA a = new FragmentA();
        a.setOnListener(new FragmentA.onListener() {
            @Override
            public void doSomeThing(String messgae) {
                //做一些需要做的事情
                Toast.makeText(MainActivity.this,messgae,Toast.LENGTH_SHORT).show();
            }
        });

        Bundle bundle = new Bundle();
        a.setArguments(bundle);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.frameLayout, a).commit();
    }


    public void showToast(String message){
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }

}

Fragment


import android.content.Intent;
import android.graphics.Bitmap;
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.Button;
import android.widget.EditText;
import android.widget.ImageView;

/**
 * Created by Think on 2016/7/19.
 */
public class FragmentA extends Fragment implements View.OnClickListener {

    private Button tiaozhuan;
    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("測試", "onCreateView");
        view = inflater.inflate(R.layout.fragment_a, null);
        tiaozhuan = (Button) view.findViewById(R.id.tiaozhuan);
        tiaozhuan.setOnClickListener(this);

        Bundle bundle = getArguments();

        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.showToast("呵呵");

        if (onListener != null) {
            onListener.doSomeThing("監聽到一些事情");
        }

        return view;
    }

    private onListener onListener;

    public void setOnListener(FragmentA.onListener onListener) {
        this.onListener = onListener;
    }

    public interface onListener {
        void doSomeThing(String messgae);
    }

}

Fragment切換時傳遞訊息:
同樣可以通過setArguments方法傳遞訊息,這裡就不多說了

那麼如果想要在一個Fragment返回上一個Fragment時將資料返回回去
可以通過setTargetFragment方法來實現
FragmentA

                FragmentB b = new FragmentB();
                b.setTargetFragment(this, 123);
                getFragmentManager().beginTransaction().hide(this)
                        .add(R.id.frameLayout, b, "Fragment")
                        .addToBackStack(null).commit();

FragmentB

                Intent intent=new Intent();
                Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
                intent.putExtra("bitmap", bitmap);
                intent.putExtra("a","你好");
                getTargetFragment().onActivityResult(123,123,intent);
                getFragmentManager().popBackStack();

FragmentB通過getTargetFragment方法來得到上一個Fragment傳遞過來的FragmentA的物件來呼叫FragmentA的onActivityResult()方法,將資料放在Intent中返回

接收的方法和Activity類似:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 123 && requestCode == 123) {
            String a = data.getStringExtra("a");
            ((EditText) view.findViewById(R.id.aet)).setText(a);
            ((ImageView) view.findViewById(R.id.image)).setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
        }
    }