通过侦听器将数据从Activity发送到片段

时间:2017-04-19 11:08:43

标签: android android-fragments interface

我有一个Activity,其中有一个ViewPager,在这个ViewPager中有一些片段。我需要在屏幕上显示数据时将数据发送到片段。所以我想在Activity中实现一个接口,将数据发送到片段。

public interface SetDataToFragment {
        void getData(List<FinanceOperationModel> aModels);
    }

public class FinanceMonitoringActivity extends ApiActivity2 implements FinanceMonitoringView
        , FinanceMonitoringFragment.SaveDataInterface {

    private SetDataToFragment mInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finance_monitoring);
        ButterKnife.bind(this);
        mInterface= (SetDataToFragment) this;
...

然后出现错误:

  

引起:java.lang.ClassCastException:com.akbars.bankok.screens.financeMonitoring.FinanceMonitoringActivity无法强制转换为com.akbars.bankok.screens.financeMonitoring.SetDataToFragment

如何正确启动活动中的界面以使用片段中的数据?

3 个答案:

答案 0 :(得分:1)

如果要将数据发送到视图寻呼机片段,可以从viewPager适配器类执行此操作,或者如果要从活动中执行,请在活动中实现接口,并从片段中调用该片段以返回所需数据。

答案 1 :(得分:0)

在Activity中创建一个接口,并通过接口将数据传递给片段。在片段中实现该接口以获取数据。

例如

<强> MainActivity.class

public class MainActivity extends AppCompatActivity {

    DataFromActivityToFragment dataFromActivityToFragment;

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

        FragmentA fr = new FragmentA();
        FragmentManager fm = getFragmentManager();
        dataFromActivityToFragment = (DataFromActivityToFragment) fr;
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_place, fr);
        fragmentTransaction.commit();


        final Handler handler = new Handler();

        final Runnable r = new Runnable() {
            public void run() {
                dataFromActivityToFragment.sendData("Hi");
            }
        };

        handler.postDelayed(r, 5000);


    }

    public interface DataFromActivityToFragment {
        void sendData(String data);
    }
}

<强> FragmentA.class

public class FragmentA extends Fragment implements MainActivity.DataFromActivityToFragment {

    TextView text;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.content_main, null);
        text = (TextView) rootView.findViewById(R.id.fragment_text);

        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void sendData(String data) {
        if(data != null)
        text.setText(data);
    }
}

答案 2 :(得分:0)

活动FinanceMonitoringActivity未实施SetDataToFragment,因此您无法将其投放到SetDataToFragment

SetDataToFragment

中实施FinanceMonitoringActivity