将数据从Activity传递到另一个,然后传递给ViewPager中的片段

时间:2016-09-28 05:52:52

标签: android android-fragments android-viewpager fragment android-bundle

我尝试将MainActivty的数据传递给ViewPager的另一个数据,并在Fragment中获取该数据。

我试过这样可能但是应用程序每次都崩溃了。

这是我的课程:

我的持有人:

@Override
public void onBindViewHolder(main_rv_holder holder, int position) {
  holder.name.setText(mains.get(position).getName());
  holder.image_main.setImageResource(mains.get(position).getImg());

  //Clicked
  holder.setItemClickListener(new ItemClickListener() {
    @Override
    public void onItemClick(View view, int position) {
      Intent intent = new Intent(context,ViewerActivity.class);
      intent.putExtra("title",mains.get(position).getName());
      intent.putExtra("pos",position);
      context.startActivity(intent);
    }
  });
}

我的寻呼机活动:

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_viewer);
  //Toolbar Initialization
  InitializeToolbar();
  //ViewPAGER Initialization
  InitializePager();
  //Floating Action Button
  Fabinitialize();

  //pass data
  Bundle data = new Bundle();
  //Use bundle to pass data
  Form1 fragmentobj = new Form1();

  data.putString("tag","Hello");
  fragmentobj.setArguments(data);
}

ViewPager中的片段:

public class Form1 extends Fragment {
  String TAG;

  public Form1() {
    TAG = getArguments().getString("tag");
    // Required empty public constructor
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment, container, false);
    TextView textView = (TextView) view.findViewById(R.id.text_VIew);
    textView.setText(TAG);

    return view;
  }
}

谢谢。

1 个答案:

答案 0 :(得分:1)

见下面的代码

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        TextView textView = (TextView) view.findViewById(R.id.text_VIew);
    String title= getActivity().getIntent().getStringExtra("title");
        textView.setText(title);

            return view;
        }
    }