There is an activity in which there is a fragment, let's call it FirstFragment. There is a framelayout in this fragment containing another fragment, SecondFragment. By clicking on SecondFragment, ThirdFragment is fired. Here, I need to be able to go back to the SecondFragment when pressing back button. However, by clicking on back button, the activity is closed. Here's my code :
MainActivity.java
public class MainActivity extends AppCompatActivity{
ViewPager viewPager;
String[] titles;
SecondFragment secondFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentPagerAdapter fragment = new FragmentPagerAdapter(getSupportFragmentManager());
viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(fragment);
firstFragment = new FirstFragment();
}
public class FragmentPagerAdapter extends android.support.v4.app.FragmentPagerAdapter {
public FragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0 : return FirstFragment.newInstance("hi");
default: return new OtherFragment();
}
}
#Override
public int getCount() {
return 3;
}
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
FirstFragment.java
public class FirstFragment extends Fragment implements RecyclerViewListener {
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Fragment secondFragment =SecondFragment.newInstance("hi");
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, secondFragment).commit();
return inflater.inflate(R.layout.fragment_first, container, false);
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void clicked(int position) {
Fragment productDetailFragment = ThirdFragment.newInstance(position);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.frameLayout, productDetailFragment).addToBackStack(null).commit();
Toast.makeText(getContext(), "pos : " + position, Toast.LENGTH_SHORT).show();
}
#Override
public boolean longClicked(int position) {
return false;
}
}
SecondFragment.java
public class SecondFragment extends Fragment {
RecyclerView recyclerView;
static ArrayList<Item> items;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_second, container, false);
recyclerView = v.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
items = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Item item = new Item(R.drawable.accept_state, "esm" + i, Integer.toString(i * 100));
items.add(item);
}
recyclerView.setAdapter(new RecylcerViewAdapter(getContext(), (RecyclerViewListener) getParentFragment(), items));
return v;
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
ThirdFragment.java
public class ThirdFragment extends android.support.v4.app.Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_third, container, false);
return v;
}
public static ThirdFragment newInstance(int position) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
f.setArguments(b);
return f;
}
}
RecyclerViewListener.java
public interface RecyclerViewListener {
void clicked(int position);
boolean longClicked(int position);
}
RecyclerViewAdapter.java
public class RecylcerViewAdapter extends RecyclerView.Adapter<RecylcerViewAdapter.RecyclerViewHolder>{
private Context context;
private RecyclerViewListener recyclerViewListener;
private ArrayList<Item> items;
public RecylcerViewAdapter(Context context, RecyclerViewListener recyclerViewListener, ArrayList<Item> items) {
this.context = context;
this.recyclerViewListener = recyclerViewListener;
this.items = items;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.bind(position);
}
#Override
public int getItemCount() {
return items.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView name;
TextView cost;
public RecyclerViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerViewListener.clicked(getAdapterPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
return recyclerViewListener.longClicked(getAdapterPosition());
}
});
imageView = itemView.findViewById(R.id.image);
name = itemView.findViewById(R.id.name);
cost = itemView.findViewById(R.id.cost);
}
public void bind(int position) {
Item item = items.get(position);
imageView.setImageResource(item.getImageID());
name.setText(item.getName());
cost.setText(item.getCost());
}
}
}
First of all, override onBackPressed() and then use use getChildFragmentManager() as shown below:
public void onBackPressed() {
// If the fragment exists and has some back-stack entry
if (myFragment != null && mytFragment.getChildFragmentManager().getBackStackEntryCount() > 0){
// Get the fragment fragment manager - and pop the backstack
myFragment.getChildFragmentManager().popBackStack();
}
// Else, nothing in the direct fragment back stack
else{
// Let super handle the back press
super.onBackPressed();
}
}
Related
I have a Viewpager contains Recylerview which has 2 different holders. One of them is also view pager. Hence I have nested viewpager nad nested fragments. When I tap the second tab and tap back the first tab it is fine .But when I tap the third tab and tap back the first tab. It gives following error:
java.lang.IllegalArgumentException: No view found for id 0x7f0f00ce (:id/viewPagerComments) for fragment CommentFragment
MainAcitivty
viewPager.setAdapter(new MainViewPagerAdapter(getSupportFragmentManager(),models.size()));
navigationTabBar.setModels(models);
navigationTabBar.setViewPager(viewPager, 0);
MainViewPagerAdapter
private int size;
public MainViewPagerAdapter(FragmentManager fm, int size) {
super(fm);
this.size = size;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return DashboardtFragment.newInstance(size, position);
default:
return TempFragment.newInstance(size, position);
}
}
DashboardtFragment
public static DashboardtFragment newInstance(int size, int index) {
Bundle args = new Bundle();
args.putInt(ARG_I,index);
args.putInt(ARG_S,size);
DashboardtFragment fragment = new DashboardtFragment();
fragment.setArguments(args);
return fragment;
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
final View v = inflater.inflate(R.layout.dashboard_fragment, null);
return v;
}
#Override
public void showRecyleview(DashboardResponseModel model) {
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
DashboardRecyleViewAdapter adapter = new DashboardRecyleViewAdapter(getActivity(),getChildFragmentManager(),model);
recyclerView.setAdapter(adapter);
}
DashboardRecyleViewAdapter
public static class ViewHolder1 extends RecyclerView.ViewHolder {
public ViewHolder1(View itemView) {
super(itemView);
viewPager = itemView.findViewById(R.id.viewPagerComments);
}
}
case 1 :
return new ViewHolder1( layoutInflater.inflate(R.layout.dashboard_comments, parent,
false));
case 1:
ViewHolder1 viewHolder1 = (ViewHolder1) holder;
viewPager.setAdapter(new CommentViewPagerAdapter(
childFragmentManager,
model.getCommentList().size(),
model.getCommentList()
));
break;
CommentViewPagerAdapter
public CommentViewPagerAdapter(FragmentManager fm, int size,
List<CommentList> list) {
super(fm);
this.size = size;
this.list=list;
}
#Override
public Fragment getItem(int position) {
return CommentFragment.newInstance(size,position,list.get(position));
}
CommentFragment
public static CommentFragment newInstance(int size, int index, CommentList
comment) {
Bundle args = new Bundle();
args.putString(ARG_C,new Gson().toJson(comment));
args.putInt(ARG_I,index);
args.putInt(ARG_S,size);
CommentFragment fragment = new CommentFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState)
{
final View v = inflater.inflate(R.layout.comment_content, null);
}
PagerAdapter mPagerAdapter;
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
super.setAdapter(null);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mPagerAdapter != null) {
super.setAdapter(mPagerAdapter);
}
}
#Override
public void setAdapter(PagerAdapter adapter) {
}
public void storeAdapter(PagerAdapter pagerAdapter) {
mPagerAdapter = pagerAdapter;
}
first create a customviewpager than add the above code. Use storeAdapter instead of setAdapter.
i have two Tabs as Tab1 and Tab2. On button click i want send list row data to send Tab , Following is my code.
PagerAdapter.java
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs = 2;
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentOne tab1 = new FragmentOne();
return tab1;
case 1:
FragmentTwo tab2 = new FragmentTwo();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
TAB 1 :
TAB 2 :
FragmentOne.java
public class FragmentOne extends Fragment implements
FirstAdapter.MyClickListner {
private RecyclerView rvMovieList;
MovieModel movieModel;
private FirstAdapter firstAdapter;
private List<MovieModel> movieList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
rvMovieList = (RecyclerView) view.findViewById(R.id.rvMovieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
rvMovieList.setLayoutManager(mLayoutManager);
rvMovieList.setItemAnimator(new DefaultItemAnimator());
new asyncGetMovie().execute();
return view;
}
#Override
public void onButtonClick(int position) {
Toast.makeText(getActivity(), "Clicked Item "+position, Toast.LENGTH_SHORT).show();
}
class asyncGetMovie extends AsyncTask<String, String, String> {
String jsonString;
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
try {
// here we get movieList
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
firstAdapter = new FirstAdapter(movieList , FragmentOne.this);
rvMovieList.setAdapter(firstAdapter);
}
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment {
private TextView tvTitle;
public FragmentTwo() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
MovieModel movieModel = null;
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
if (movieModel != null){
movieModel = getArguments().getParcelable("data");
System.out.println(" movieModel title "+movieModel.getTitle());
tvTitle.setText(movieModel.getTitle());
}
return view;
}
}
FirstAdapter.java
public class FirstAdapter extends
RecyclerView.Adapter<FirstAdapter.MyViewHolder> {
private MyClickListner clickListner;
private List<MovieModel> moviesList;
FragmentOne fragament ;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
Button btnDetails;
MyClickListner clickListner;
public MyViewHolder(View view) {
super(view);
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
btnDetails = (Button)view.findViewById(R.id.btnDetails);
}
}
public FirstAdapter(List<MovieModel> moviesList, FragmentOne fragmentOne) {
this.moviesList = moviesList;
this.fragament = fragmentOne;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_movie_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
MovieModel movie = moviesList.get(position);
holder.tvTitle.setText(movie.getTitle());
holder.btnDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragament.onButtonClick(position);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
public interface MyClickListner{
public void onButtonClick(int position);
}
}
Change you getItem()
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentOne tab1 = new FragmentOne();
return tab1;
case 1:
FragmentTwo tab2 = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putExtra("KEY_OF_WHATEVER_YOU_WANT_TO_SEND","VALUE");
tab2.setArguments(bundle);
return tab2;
default:
return null;
}
}
I want to change the Fragment when i click the button. The fragments are in the same adapter/viewpager.
FROM THIS FRAGMENT:
public class LoginFragment extends Fragment {
TextView linkToRegister;
public static final LoginFragment newInstance()
{
LoginFragment mf = new LoginFragment();
Bundle bd = new Bundle(1);
mf.setArguments(bd);
return mf;
}
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState )
{
View v = inflater.inflate(R.layout.fragment_login, container, false);
linkToRegister = (TextView) v.findViewById(R.id.link_to_register);
linkToRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Change Fragment
}
});
return v;
}
}
TO THIS FRAGMENT:
public class RegisterFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final RegisterFragment newInstance()
{
RegisterFragment mf = new RegisterFragment();
Bundle bd = new Bundle(1);
mf.setArguments(bd);
return mf;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View v = inflater.inflate(R.layout.fragment_register, container, false);
return v;
}
}
PagerAdapter:
public class WelcomePagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> Welcomefragments;
public WelcomePagerAdapter(FragmentManager fm, List<Fragment> Welcomefragments) {
super(fm);
this.Welcomefragments = Welcomefragments;
}
#Override
public Fragment getItem(int position) {
return this.Welcomefragments.get(position);
}
#Override
public int getCount() {
return this.Welcomefragments.size();
}
}
Activity:
public class WelcomeActivity extends AppCompatActivity {
ViewPager welcomeViewPager;
WelcomePagerAdapter welcomePagerAdapter;
List<Fragment> welcomeFragments;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
welcomeViewPager = (ViewPager) findViewById(R.id.viewPagerWelcome);
welcomeFragments = getWelcomeFragments();
welcomePagerAdapter = new WelcomePagerAdapter(getSupportFragmentManager(), welcomeFragments);
welcomeViewPager.setAdapter(welcomePagerAdapter);
}
public List<Fragment> getWelcomeFragments() {
List<Fragment> newFragment = new ArrayList<Fragment>();
newFragment.add(LoginFragment.newInstance());
newFragment.add(RegisterFragment.newInstance());
return newFragment;
}
}
Step 1: Define a callback interface in the Fragment and hook in the Activity when the Fragment attaches to it.
public class MyFragment extends Fragment {
public interface OnInteractionListener {
void doAction(); // Can include parameters here if needed
}
private OnInteractionListener listener;
#Override
public void onAttach(Context context) {
if (context instanceof OnInteractionListener) {
listener = (OnInteractionListener) context;
} else {
throw new ClassCastException(context + "must implement " + OnInteractionListener.class.getSimpleName());
}
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// ...
return v;
}
}
Step 2: Make sure your Activity implements that Interface
public class MyActivity extends AppCompatActivity implements MyFragment.OnInteractionListener {
#Override
public void doAction() {
// TODO: Implement this... e.g. switch fragments
}
...
}
Step 3: Inside the Fragment, you can invoke the callback whenever you want to perform some action
if (listener != null) {
listener.doAction();
}
From MainActivity(), get the navController and then use the navigate() function:
NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);
navController.navigate(R.id.nav_grid);
This is very simplified problem that I have regarding to Fragments and calling methods between fragments. I have put in the code place where I think calling method should be. Correct me if I'm wrong or if you have right solution for my problem. MainFragment extends Fragment because it is not activity... I have navigation drawer so that is how it suppose to be... :)
public class MainFragment extends Fragment{
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container, false);
adapter = new CategoriesPagerAdapter(getChildFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// ...here I need to call method "writeText()" in both fragments to update both TextViews also in both fragments (tabs)
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Tab1Class tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
Tab2Class tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
Tab2Class:
public class Tab1Class extends Fragment {
TextView tv1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tv1 = (TextView) rootView.findViewById(R.id.tv1);
writeText();
}
public void writeText(){
tv1.setText("TV1 text");
}
}
Tab1Class:
public class Tab2Class extends Fragment {
TextView tv2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
tv2 = (TextView) rootView.findViewById(R.id.tv2);
writeText();
}
public void writeText(){
tv2.setText("TV2 text");
}
}
.
.
.
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/////////////////////////Added////////////
adapter.callWrite();
////////////////////////////////////////
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
/////////////////////Added///////////////////
Tab1Class tab1;
Tab2Class tab2;
//////////////////////////////
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
////////////////////////////Added////////////////////
public void callWrite(){
if(tab1 != null)
tab1.writeText();
if(tab2 != null)
tab2.writeText();
}
/////////////
.
.
.
Here's an alternative:
public class BlankFragment extends Fragment {
public static final String ACTION_SOME_STUFF_HAPPENED = "stuff_happened_yo";
public static final String EXTRA_STUFF = "this_is_stuff";
public static void notifyStuffHappening(Context context, String stuff){
Intent intent = new Intent(ACTION_SOME_STUFF_HAPPENED);
intent.putExtra(EXTRA_STUFF, stuff);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private StuffHappenedReceiver mStuffListener;
public static class StuffHappenedReceiver extends BroadcastReceiver {
final BlankFragment mFragment;
public StuffHappenedReceiver(BlankFragment fragment) {
this.mFragment = fragment;
// listen for changes to the account we're using
IntentFilter filter = new IntentFilter(ACTION_SOME_STUFF_HAPPENED);
LocalBroadcastManager.getInstance(fragment.getContext()).registerReceiver(this, filter);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_SOME_STUFF_HAPPENED.equals(action)) {
mFragment.someStuffHappened(intent.getStringExtra(EXTRA_STUFF));
}
}
}
private void someStuffHappened(String stringExtra) {
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mStuffListener = new StuffHappenedReceiver(this);
}
#Override
public void onDetach() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mStuffListener);
mStuffListener = null;
super.onDetach();
}
}
This shows the basics of a fragment that will register a broadcast receiver automatically as it attaches / detaches from the activity.
If the fragment is not attached, it won't be updated.
To update this fragment, call the static method "notifyStuffHappening"
in my App i have Gridview and TabActivity.
my Rice.class has gridview,
in MainActivity.class has tabActivity ,
myChild Tabs are FragmentA,FragmentB,FragmnetC.
i want pass my gridview index to FragmnetA.how can i slove this problem.
Rice.class
public class Rice extends ActionBarActivity {
FragmentA fa;
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rice);
gridView=(GridView) findViewById(R.id.gridViewR);
gridView.setAdapter(new MyRAdapter(this));
Intent intent = getIntent();
//Breakfast bf = (Breakfast) getFragmentManager().findFragmentById(R.id.fragment2);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("index",i);
startActivity(intent);
}
});
}
}
class MyRAdapter extends BaseAdapter {
private Context mContext;
public MyRAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
//imageView.setLayoutParams(new GridView.LayoutParams(450, 200));
//imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
private Integer[] mThumbIds = {
R.drawable.back_1, R.drawable.back_2,
R.drawable.back_3, R.drawable.back_4,
R.drawable.back_5, R.drawable.back_6,
R.drawable.back_11,
};
}
MainActivity.class
public class MainActivity extends FragmentActivity {
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyFrAdapter(fragmentManager));
Intent intent = getIntent();
int index = intent.getIntExtra("index",0);
}
}
class MyFrAdapter extends FragmentPagerAdapter{
public MyFrAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if(i==0){
fragment = new FragmentA();
}
if(i==1){
fragment = new FragmentB();
}
if(i==2){
fragment = new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Ingredient";
}
if(position == 1){
return "Recipe";
}
if(position == 2){
return "Summary";
}
return null;
}
}
FragmentA.class
public class FragmentA extends Fragment {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a,container,false);
textView = (TextView) view.findViewById(R.id.textView);
return view;
}
}
public class MainActivity extends FragmentActivity {
int mIndex;
ViewPager viewPager=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyFrAdapter(fragmentManager));
Intent intent = getIntent();
mIndex = intent.getIntExtra("index",0);
}
class MyFrAdapter extends FragmentPagerAdapter{
public MyFrAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if(i==0){
fragment = new FragmentA().newInstance(mIndex);
}
if(i==1){
fragment = new FragmentB();
}
if(i==2){
fragment = new FragmentC();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "Ingredient";
}
if(position == 1){
return "Recipe";
}
if(position == 2){
return "Summary";
}
return null;
}
}
}
//...
public class FragmentA extends Fragment {
TextView textView;
int FragmentA_index;
public static final String EXTRA_INDEX = "mypackage.index";
public static FragmentA newInstance(int index) {
Bundle args = new Bundle();
args.putInt(EXTRA_INDEX, index);
FragmentA fragment = new FragmentA();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentA_index = getArguments().getInt(EXTRA_INDEX);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a,container,false);
textView = (TextView) view.findViewById(R.id.textView);
return view;
}
}