将值从活动发送到其片段

时间:2018-06-08 02:33:25

标签: android android-fragments

我试图将活动类中的数据发送到其标签片段,但在片段适配器中它没有收到数据并产生错误nullPointerException。

这是我的代码

来自活动

ctx.fillStyle

到片段

Intent receivedIntent = getIntent();
    String tenant = null;
    if ((bundle = receivedIntent.getExtras()) != null) {
        tenant = (String) bundle.get("tenant");
    }

    TabFragment tabFragment = new TabFragment();
    bundle.putString("tenant", tenant);
    tabFragment.setArguments(bundle);

寻呼机适配器

Bundle getTenant = this.getArguments();
    if(getTenant != null) {
        tenant = getTenant.getString("tenant");
        System.out.println("Tab fragment: " + tenant);
    }else {
        System.out.println("Tab fragment: null");
    }

2 个答案:

答案 0 :(得分:0)

在您的片段中执行此操作

use PHPExcel_Settings;
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);

而不是

if(getArguments() != null) {
    tenant = getArguments().getString("tenant");
    System.out.println("Tab fragment: " + tenant);
}else {
    System.out.println("Tab fragment: null");
}

答案 1 :(得分:0)

使用以下代码:

 Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

并在Fragment onCreateView方法中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

另一种方法您可以使用如下界面传递数据:
第1步:我在我的Activity和setter中创建了公共接口:

    Private OnAboutDataReceivedListener mAboutDataListener;
      public interface OnAboutDataReceivedListener {
        void onDataReceived(YourModelClass model);
    }

     public void setAboutDataListener(OnAboutDataReceivedListener listener) {
        this.mAboutDataListener = listener;
      }

2步:我在Fragment中实现了这个接口并设置了listener:

public class YourActivity extends BaseFragment implements YourBaseActivity.OnAboutDataReceivedListener

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

            mActivity = (YourActivity) getActivity();
            mActivity.setAboutDataListener(this);
        }

3步:我重写了界面的方法:

    @Override
    public void onDataReceived(YourClassModel model) {
    }