Skip to content

Instantly share code, notes, and snippets.

@gunhansancar
Last active October 29, 2015 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunhansancar/2ca2ec017e79d54e2273 to your computer and use it in GitHub Desktop.
Save gunhansancar/2ca2ec017e79d54e2273 to your computer and use it in GitHub Desktop.
This is a sample fragment which demonstrates how to properly instantiate a fragment with arguments.
package com.gunhansancar.android.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Sample fragment to demonstrate the instantiation of fragments with arguments
*
* Created by Günhan on 28.10.2015.
*/
public class MyFragment extends Fragment {
private String name;
private int age;
private TextView mNameTextView;
private TextView mAgeTextView;
public static MyFragment newInstance(String name, int age) {
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putInt("age", age);
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
return fragment;
}
private void readBundle(Bundle bundle) {
if (bundle != null) {
name = bundle.getString("name");
age = bundle.getInt("age");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
mNameTextView = (TextView) view.findViewById(R.id.nameTextView);
mAgeTextView = (TextView) view.findViewById(R.id.ageTextView);
readBundle(getArguments());
mNameTextView.setText(String.format("Name: %s", name));
mAgeTextView.setText(String.format("Age: %d", age));
return view;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment