将值传递给片段

时间:2014-10-08 06:58:03

标签: android android-fragments android-viewpager

我正在创建一个应用程序,其中我想要滑动图像,所以为此我将使用视图寻呼机。对于图像我创建了一个片段,将显示图像。 代码

public class ImageSwitcher extends BaseFragment {

    private ImageView imageView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initialize();
    }

    private void initialize() {
        imageView = (ImageView) view.findViewById(R.id.image_switcher);
        imageView.setBackgroundResource("");
    }

现在就在这一行

imageView.setBackgroundResource("");

图像将来自我将通过的int数组。 我怀疑是

  1. 我如何将int值传递给片段
  2. 有没有更好的方法来使用图像切换器

3 个答案:

答案 0 :(得分:1)

使用Integer传递您的片段中的Bundle值,如下所示:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
 bundle.putInt("id", id);
 fragment.setArguments(bundle); 

访问Fragment onCreateView方法中的值:

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

     int m_id=getArguments().getInt("id");

return inflater.inflate(R.layout.fragment, container, false);
}

答案 1 :(得分:0)

您可以使用bundle将值传递给片段,或者在通过custom构造函数初始化传递值时

对于后台资源,如果您没有根据代码中的某些逻辑更改图像,请通过XML背景和drawable应用它: - /

答案 2 :(得分:0)

class MyFragment extends Fragment {

private static final String ARG_BG_RES="ARG_BG_RES";

public Fragment() {}

static public newInstance(String backgroundRes) {
   Bundle args = new Bundle();
   args.putExtra(ARG_BG_RES, backgroundRes);
   Fragment fragment = new Fragment();
   fragment.setArguments(args);
   return f;

void whereYouNeedIt() {
   String backgroundRes = getArguments().getStringExtra(ARG_BG_RES);
   ...
}

}

从外面看:

MyFragment f = MyFragment.newInstance("black");

不要忽略操作系统要求的public Fragment() {}

相关问题