Anuj
Anuj

Reputation: 29

Pass value to fragment

I am creating a app in which i wanna slide images,so for that i will be using view pager.For the image i have created a fragment which will display the images. Code

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("");
    }

Now at this line

imageView.setBackgroundResource("");

the image will come from the int array which i will pass. My doubt is

  1. How will i pass int values to fragments
  2. Is there any better way to use image switcher

Upvotes: 1

Views: 59

Answers (3)

Alexander
Alexander

Reputation: 48252

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);
   ...
}

}

From outside:

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

Don't omit public Fragment() {} it's required by the OS.

Upvotes: 0

GrIsHu
GrIsHu

Reputation: 23638

Pass your Integer value from your fragment using Bundle as below:

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

Access the value in Fragment onCreateView method:

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

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

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

Upvotes: 1

Panther
Panther

Reputation: 9408

You can use bundle to pass values to the fragment or during initializing pass values via a custom constructor

For background resource if you are not changing images based on some logic in code, apply it via XML background and a drawable :-/

Upvotes: 0

Related Questions