fragment和activity之间进行数据交互

Posted wukj_litai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fragment和activity之间进行数据交互相关的知识,希望对你有一定的参考价值。

fragmnt 在现在的应用中使用的很多,fragment 和activity之间需要进行数据的交互。本文将从以下二个小的例子,第一个fragment在创建的时候获取从activity传过来的参数,第二个activity获取fragment 中的参数。

首先看第一个 activity中创建 fragment的时候,需要传递数据给fragment,我们可以这样做:

在activity 中:

 dutyDepartmentFragment = new DutyDepartmentFragment();
        Bundle Rbundle = new Bundle();
        Rbundle.putString("petitionFileId",petitionFileId);
        Rbundle.putString("pRState",pRState);
        Rbundle.putString("pRDegree",pRDegree);
        Rbundle.putString("pRNote",pRNote);
        dutyDepartmentFragment.setArguments(Rbundle);

在对应的fragment中,我们要获取这些参数很简单:

 petitionFileId = getArguments().getString("petitionFileId");
        pRState = getArguments().getString("pRState");
        pRDegree = getArguments().getString("pRDegree");
        pRNote = getArguments().getString("pRNote");

如果我们想在activity中获取fragment中的参数,可以使用接口回调的思想来实现。下面是我的一个小的demo,这个例子是这样的,在一个activity中有二个fragment,我们希望在activity中点击一个按钮之后就能获取在fragment 中的指定参数。

activity的代码

public class MainActivity extends AppCompatActivity implements FragmentOne.sendReslut 


    private Button button_submit;// 提交按钮
    private TextView tv_petition_deparement;// 对信访部门评价
    private TextView tv_duty_deparment;// 对责任部门评价
    private View View_Line;// 选择线
    private ViewPager viewPager;// viewpager
    private FragmentOne fragmentOne;
    private FragmentTwo fragmentTwo;
    private ArrayList<Fragment> fragments;
    private FragmentAdapter fragmentAdapter;
    private int currIndex = 0;
    private int tabLineLength;

    private Resources resource;
    private ColorStateList csl;
    private ColorStateList csl_hint;


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

    private void initView() 
        // 初始化化控件
        button_submit = (Button) findViewById(R.id.button_submit);
        tv_petition_deparement = (TextView) findViewById(R.id.tv_petition_deparement);
        tv_duty_deparment = (TextView) findViewById(R.id.tv_duty_deparment);
        View_Line = (View) findViewById(R.id.View_Line);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        fragmentOne = new FragmentOne();
        fragmentTwo = new FragmentTwo();
        fragments = new ArrayList<Fragment>();
        fragments.add(fragmentOne);
        fragments.add(fragmentTwo);

        fragmentAdapter = new FragmentAdapter(this.getSupportFragmentManager(), fragments);
        viewPager.setAdapter(fragmentAdapter);
        viewPager.setCurrentItem(currIndex);

        Display display = getWindow().getWindowManager().getDefaultDisplay();
        // 得到显示屏宽度
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        // 1/3屏幕宽度
        tabLineLength = metrics.widthPixels / 2;
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) View_Line.getLayoutParams();
        lp.width = tabLineLength;
        View_Line.setLayoutParams(lp);

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() 
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) 

                LinearLayout.LayoutParams ll = (android.widget.LinearLayout.LayoutParams) View_Line
                        .getLayoutParams();

                if (currIndex == position) 
                    ll.leftMargin = (int) (currIndex * tabLineLength + positionOffset
                            * tabLineLength);
                 else if (currIndex > position) 
                    ll.leftMargin = (int) (currIndex * tabLineLength - (1 - positionOffset) * tabLineLength);
                
                View_Line.setLayoutParams(ll);

            

            @Override
            public void onPageSelected(int position) 
                currIndex = position;

                if (position == 0) 
                    tv_petition_deparement.setTextColor(csl);
                    tv_duty_deparment.setTextColor(csl_hint);

                 else 
                    tv_petition_deparement.setTextColor(csl_hint);
                    tv_duty_deparment.setTextColor(csl);
                
            

            @Override
            public void onPageScrollStateChanged(int state) 

            
        );

        resource = (Resources) getBaseContext().getResources();
        csl = (ColorStateList) resource.getColorStateList(R.color.textColor);
        csl_hint = (ColorStateList) resource.getColorStateList(R.color.hintTextColor);

        tv_petition_deparement.setTextColor(csl);
        tv_duty_deparment.setTextColor(csl_hint);

        tv_petition_deparement.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                //
                tv_petition_deparement.setTextColor(csl);
                tv_duty_deparment.setTextColor(csl_hint);
                viewPager.setCurrentItem(0);
                currIndex = 0;

            
        );
        tv_duty_deparment.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                tv_petition_deparement.setTextColor(csl_hint);
                tv_duty_deparment.setTextColor(csl);
                viewPager.setCurrentItem(1);
                currIndex = 1;
            
        );

        // 点击提交按钮之后,调用 fragmentOne 的方法,进而回调接口
        button_submit.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                // activity 中 调用fragment中的方法,返回 fragment 中的参数
                fragmentOne.postData();
            
        );


    

    // 通过回调接口把fragment的数据传递给activity
    @Override
    public void send(String data) 
        Toast.makeText(getApplicationContext(), data, Toast.LENGTH_SHORT).show();
    

有回调接口的fragment

public class FragmentOne extends Fragment 

    private sendReslut sendresult;
    @Override
    public void onAttach(Context context) 
        super.onAttach(context);
        sendresult = (sendReslut) getActivity();
    

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
    

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 

        View view = inflater.inflate(R.layout.fragment_one,null);
        return view;
    

    public void postData()
        sendresult.send("这是测试数据");
    


     public interface sendReslut
         public void send(String data);
     

上面的代码也比较简单,通过一个简单的接口,我们就实现了fragment给activity传递数据,整个项目的代码:

代码

以上是关于fragment和activity之间进行数据交互的主要内容,如果未能解决你的问题,请参考以下文章

Android进阶之Fragment与Activity之间的数据交互

Android中Fragment与Activity之间的交互(两种实现方式)

fragment之间的信息交互——onActivityResult()不经过Activity

Activity 和 Fragment 交互

activity与fragment之间传递数据

Android Fragment