How to edit a fragment and save its state? - android

I have to add TextViews and EditTexts in a Fragment ( Details() ) when i click in a button ( Button add ).
I was able to insert them, but when i swipe my 6 fragments and return in the first fragment this items disappear.
Can someone help me?
FragmentActivity class:
public class SubActivityTab extends FragmentActivity
{
SectionsPagerAdapter spa;
ViewPager vp;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scrolltab_layout);
spa = new SectionsPagerAdapter(getSupportFragmentManager(), this);
vp = (ViewPager) findViewById(R.id.pager);
vp.setAdapter(spa);
}
}
FragmentPagerAdapter class:
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
Context c;
public SectionsPagerAdapter(FragmentManager fm, Context c) {
super(fm);
this.c = c;
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
return Details.newInstance();
...
}
return null;
}
#Override
public int getCount() {
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position)
{
case 0:
return c.getString(R.string.tab1).toUpperCase(l);
...
}
return null;
}
}
Fragment class:
public final class Details extends Fragment {
public static View layout;
public static LinearLayout ll;
public static Details newInstance()
{
return new Details();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
layout = inflater.inflate(R.layout.details, container, false);
ll = (LinearLayout) layout.findViewById(R.id.linearlayout2);
Button add = (Button) layout.findViewById(R.id.button_add);
add.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
insertLine();
insertClassEditText();
insertLevel();
}});
return layout;
}
private void insertLine()
{
View temp = (View) layout.findViewById(R.id.line);
View v = new View(temp.getContext());
v.setBackgroundColor(Color.rgb(209, 209, 209));
v.setId(0);
v.setLayoutParams(temp.getLayoutParams());
ll.addView(v);
}
private void insertClassEditText()
{
TextView label_classe = (TextView) layout.findViewById(R.id.textView10);
EditText edit_classe = (EditText) layout.findViewById(R.id.editText9);
TextView new_label_classe = new TextView(label_classe.getContext());
EditText new_edit_classe = new EditText(edit_classe.getContext());
new_label_classe.setId(1);
new_edit_classe.setId(2);
new_label_classe.setText("Label");
new_label_classe.setTextAppearance(new_label_classe.getContext(), android.R.style.TextAppearance_Medium);
ll.addView(new_label_classe);
new_edit_classe.setInputType(edit_classe.getInputType());
new_edit_classe.setLayoutParams(edit_classe.getLayoutParams());
ll.addView(new_edit_classe);
}
private void insertLevel()
{
TextView label_lv = (TextView) layout.findViewById(R.id.textView11);
EditText edit_lv = (EditText) layout.findViewById(R.id.editText10);
TextView new_label_lv = new TextView(label_lv.getContext());
EditText new_edit_lv = new EditText(edit_lv.getContext());
new_label_lv.setId(3);
new_edit_lv.setId(4);
new_label_lv.setText(label_lv.getText());
new_label_lv.setTextAppearance(new_label_lv.getContext(), android.R.style.TextAppearance_Medium);
ll.addView(new_label_lv);
new_edit_lv.setInputType(edit_lv.getInputType());
new_edit_lv.setLayoutParams(edit_lv.getLayoutParams());
ll.addView(new_edit_lv);
}
}

I believe ViewPager recycles the views as you swipe and therefore when you go back, it rebuilds from onCreateView.
I would suggest setting some tags and passing to onSaveInstanceState.
private void onSaveInstanceState(Bundle b) {
if (label_classe != null) {
b.putBoolean("label_classe", true);
}
}
Then in onCreateView you take savedInstanceState, check what elements were created and re-create them.
So in Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
....
if (savedInstanceState.getBoolean("label_classe")) {
insertClassEditText();
}
....
}
And just to be sure, in Activity:
public class SubActivityTab extends FragmentActivity
{
SectionsPagerAdapter spa;
ViewPager vp;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.scrolltab_layout);
spa = new SectionsPagerAdapter(getSupportFragmentManager(), this);
vp = (ViewPager) findViewById(R.id.pager);
vp.setSaveState(true);
vp.setSaveFromParentEnabled(true);
vp.setAdapter(spa);
}
}

Try to change your onCreateView method to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
if(layout ==null){
layout = inflater.inflate(R.layout.details, container, false); //Dont inflate every time.layout saved, data of layout,like EidtText also saved.
}
ViewParent parent = mLayout.getParent();
if(parent!=null){
((ViewGroup)parent).removeView(layout);//the view will be add to NoSaveStateFrameLayout after onCreateView,so remove self everytime
}
return layout;
}

Related

How to get fragment index from within itself?

I have 3 fragments that are generated from the same class file. These three fragments exist within a ViewPager and a FragmentStatePagerAdapter.
They are in sliding tabs. They are created once and never dismissed or deleted or go out of memory.
The app works fine so far, but I need to figure out how to make the fragments have knowledge of their own index (1,2, or 3).
Is there some code like:
int myIndex = summonTheAllKnowingThing.getWhatFragmentThisIsPlease();
That I can add somewhere in the following code?
public class BlankFragment extends Fragment implements View.OnClickListener {
private boolean isDone = false;
EditText persons_name;
Spinner disc1_spinner;
Spinner disc2_spinner;
Spinner disc3_spinner;
Spinner fee1_spinner;
Spinner fee2_spinner;
EditText custom_disc;
EditText custom_fee;
Button doneButton;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance() {
BlankFragment fragment = new BlankFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_blank, container, false);
doneButton = (Button) v.findViewById(R.id.doneButton);
doneButton.setOnClickListener(this);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// getView().findViewById(R.id.
persons_name = (EditText) getView().findViewById(R.id.NAME);
disc1_spinner = (Spinner) getView().findViewById(R.id.DISC1);
disc2_spinner = (Spinner) getView().findViewById(R.id.DISC2);
disc3_spinner = (Spinner) getView().findViewById(R.id.DISC3);
custom_disc = (EditText) getView().findViewById(R.id.customDISC);
custom_fee = (EditText) getView().findViewById(R.id.customFEE);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.doneButton:
if MainActivity.is1Done
doneButton.setBackgroundColor(Color.RED);
MainActivity.name1 = persons_name.getText().toString();
break;
}
}
}
Best approach is to pass the index while creating the fragment in pager adapter as in
#Override
public Fragment getItem(int position) {
return BlankFragment.newInstance(position);
}
and BlankFragment would be
public class BlankFragment extends Fragment implements View.OnClickListener {
private int myIndex; //<-- access it for getting its index
//.. some other variables
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(int indexInPager) {
BlankFragment fragment = new BlankFragment();
Bundle bundle = new Bundle();
bundle.putInt("index",indexInPager);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myIndex = getArguments().getInt("index");
View v = inflater.inflate(R.layout.fragment_blank, container, false);
doneButton = (Button) v.findViewById(R.id.doneButton);
doneButton.setOnClickListener(this);
return v;
}
//.. some other code
}

No view found for id ... for fragment in a Dialog

I want show 2 tabs in a custom Dialog in an Activity, but I am getting the following error.
Error:
No view found for id 0x7f0f0134 (com.hiro.chatio:id/viewPage_theme) for fragment
PostColorPickerFragment{35ffefce #0 id=0x7f0f0134 android:switcher:2131689780:0}
java.lang.IllegalArgumentException: No view found for id 0x7f0f0134 (com.hiro.chatio:id/viewPage_theme)
for fragment PostColorPickerFragment{35ffefce #0 id=0x7f0f0134 android:switcher:2131689780:0}
MainActivity:
private Button pick_color;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_blog);
pick_color = (Button) findViewById(R.id.create_blog_color_btn);
pick_color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(CreateBlogActivity.this);
dialog.setContentView(R.layout.blog_theme_picker);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().getAttributes().windowAnimations = R.style.SlideUpDialogAnimation;
Button pickColor = (Button) dialog.findViewById(R.id.pick_color_btn);
Button default_color = (Button) dialog.findViewById(R.id.default_color);
TabLayout mTabLayout = (TabLayout) dialog.findViewById(R.id.main_tabs_theme);
CustomViewPager mViewPager = (CustomViewPager) dialog.findViewById(R.id.viewPage_theme);
ThemePagerAdapter mThemePagerAdapter = new ThemePagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mThemePagerAdapter);
mViewPager.setCurrentItem(0);
mViewPager.setPagingEnabled(false);
mTabLayout.setupWithViewPager(mViewPager); }); }
ThemePagerAdapter:
public class ThemePagerAdapter extends FragmentPagerAdapter {
public ThemePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
PostColorPickerFragment postColorPickerFragment = new PostColorPickerFragment();
return postColorPickerFragment;
case 1:
PostThemePickerFragment postThemePickerFragment = new PostThemePickerFragment();
return postThemePickerFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Color";
case 1:
return "Theme";
default:
return null;
}
}
PostThemePickerFragment:
public class PostThemePickerFragment extends Fragment {
public PostThemePickerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.post_theme_picker, container, false);
return view;
}
You're getting that Exception because the Activity's FragmentManager cannot find Views in a Dialog, as its layout is not attached to the Activity's hierarchy. In order to use Fragments in a Dialog, you'll have to use a DialogFragment, passing its child FragmentManager to the PagerAdapter to handle the transactions.
As with any regular Fragment, we can inflate the layout in onCreateView(), and set it up in onViewCreated(). We'll also override the onCreateDialog() method to modify the window settings there.
public class ThemeDialogFragment extends DialogFragment {
public ThemeDialogFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.blog_theme_picker, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Button pickColor = (Button) view.findViewById(R.id.pick_color_btn);
Button default_color = (Button) view.findViewById(R.id.default_color);
TabLayout mTabLayout = (TabLayout) view.findViewById(R.id.main_tabs_theme);
CustomViewPager mViewPager = (CustomViewPager) view.findViewById(R.id.viewPage_theme);
ThemePagerAdapter mThemePagerAdapter = new ThemePagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(mThemePagerAdapter);
mViewPager.setCurrentItem(0);
mViewPager.setPagingEnabled(false);
mTabLayout.setupWithViewPager(mViewPager);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog d = super.onCreateDialog(savedInstanceState);
d.getWindow().getAttributes().windowAnimations = R.style.SlideUpDialogAnimation;
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setCanceledOnTouchOutside(false);
return d;
}
}
You can see that everything you had in the onClick() method is now handled in the DialogFragment, and that method becomes simply:
pick_color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new ThemeDialogFragment().show(getSupportFragmentManager(), "theme");
}
}
);

TextView from ViewPager is throwing Null Pointer Exception

I have a fragment with a ViewPager inside it. In the ViewPager I have 4 content screens so swipe around in. The content has a few TextView components and I'm trying to access them from the first fragment, however when I go to use setText or similar I get a null pointer exception. Ive checked and the id for the TextView is valid, and I've done a clean build.
Here is a snippet of my relevant code:
private TextView textViewOne;
private PagerAdapter mPagerAdapter;
private ViewPager pager;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_viewpager, container, false);
InitializePaging();
textViewOne = (TextView) rootView.findViewById(R.id.create_name);
//would return null if I did this:
textViewOne.setText("test");
return rootView;
}
private void InitializePaging() {
mPagerAdapter = new ViewPagerAdapter(getContext(), getChildFragmentManager(),
Arrays.asList(PageOne.class, PageTwo.class, PageThree.class, PageFour.class));
pager = (ViewPager) rootView.findViewById(R.id.content_pager);
pager.setAdapter(mPagerAdapter);
}
The PageOne class:
public class PageOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container == null) {
return null;
}
return (LinearLayout) inflater.inflate(R.layout.fragment_page_one, container, false);
}
}
This is the fragment_layout_viewpager xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/content_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
You are inflating fragment_layout_viewpager, so the create_name should exist in that layout, otherwise it will throw a null pointer.
Create an interface with 1 abstract method. Let the Fragment implement the interface and call the callback method from Activity.In the below example, I try to pass value on click of button from MainActivity to ThirdFragment.
public interface FragmentCommunicator {
public void passDataToFragment(String someValue);
}
public class MainActivity extends FragmentActivity {
FragmentCommunicator fragmentCommunicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn= (Button)findViewById(R.id.button) ;
btnsetOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
randomvalue= getRansomString();
if(fragmentCommunicator!=null)
fragmentCommunicator.passDataToFragment(randomvalue);
}
});
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return FirstFragment.newInstance("FirstFragment,Instance 1");
}
}
#Override
public int getCount() {
return 2;
}
}
public static class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(getArguments().getString("msg"));
return v;
}
public static FirstFragment newInstance(String text) {
Log.e("FirstFragment","newInstance called");
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
public class ThirdFragment extends Fragment implements FragmentCommunicator {
TextView tv;
String value="";
public FragmentCommunicator fragmentCommunicator;
#Override
public void passDataToFragment(String someValue) {
this.value = someValue;
tv.setText(value);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
((MainActivity)activity).fragmentCommunicator = this;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FragmentCommunicator");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
value=getArguments().getString("msg");
tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText(value);
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg",text);
f.setArguments(b);
return f;
}
}

how to access the value of edittext inside fragment which is in a viewpager

I am having am mainActivity which consists of 3 fragment activity in a view pager .each fragment consists of edit texts .How to get the value of the edit text when swipe fragment horizontally ? I am trying to do like this.below code
public class MainActivity extends FragmentActivity {
int value = 0;
Context context;
String a = "";
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
// Set up the action bar.
//final ActionBar actionBar = getActionBar();
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mAddButtonB = (Button) findViewById(R.id.addnewB);
mAddSearchV = findViewById(R.id.addnewSearch);
mAddButtonB.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mAddSearchV.setVisibility(View.GONE);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.customviewpager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
});
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
PageZero p0;
PageOne p1;
PageTwo p2;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
p0 = new PageZero();
p1 = new PageOne();
p2 = new PageTwo();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return p0;
case 1:
return p1;
case 2:
return p2;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
// PageZero = (Fragment1)getFragmentManager().findFragmentByTag("frag1");
public class PageZero extends Fragment {
private EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container,
false);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});/*(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(), a,Toast.LENGTH_SHORT).show();
return false;
}
});*/
return view;
}
}
public class PageOne extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentaddress, container,
false);
return view;
}
}
public class PageTwo extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentmobno, container,
false);
return view;
}
}
}
when i try to access the eddittext inside pageZero class like below
name=(EditText)view.findViewById(R.id.nameTV);
a=name.getText().toString().trim();
i am getting null value.help me out..Thanks in advance.
Change the pagezero class oncreateview code like this .....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =getActivity().getLayoutInflater().inflate(R.layout.componentname,null);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
return view;
});
Return the view friend and then use default layout inflater...
At the time you click the edittext field, is there any content? Maybe you should get the text in the lost focus event of the edittext field. Thus you can enter some text first...
Example:
name.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus == false){
//get text from edittext field...
}
}
});
The way you try to get the text looks right to me. At least I do it the same way.
In the PagerAdapter's 'getItem' Method you should instantiate your fragments directly:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new PageZero();
case 1:
return new PageOne();
case 2:
return new PageTwo();
}
return null;
}
The Viewpager only calls getItem if it wants to create a new item. Unfortunatly they called the method getItem and not createItem which would be more obvious.
Get your EditText inside onClick block...
This mean change the code from:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container, false);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});
return view;
}
To:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container, false);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// GET EDIT TEXT HEAR:
EditText name=(EditText)view.findViewById(R.id.nameTV);
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});
return view;
}
To create a 3 different fragments with view pager you should:
1)Create FragmentActivity with view pager and view pager adapter.
public class FragmentActivity extends FragmentActivity
{
private FragmentAdapter adapter;
private ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
adapter = new FragmentAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
}
2)Create 3 Fragments with static instance
public final class Fragment1 extends Fragment
{
public static Fragment1 newInstance() {
return new Fragment1();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout layout = new LinearLayout(getActivity());
// your fragment xml view
return view;
}
}
3)Fill view pager adapter with it;
public class FragmentAdapter extends FragmentPagerAdapter
{
public InstallFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Fragment1.newInstance();
case 1:
return Fragment2.newInstance();
case 2:
return Fragment3.newInstance();
}
return null;
}
}
public class PageZero extends Fragment {
public static EditText name; //change this to public static
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container,
false);
name = (EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return view;
}
}
Then, you can access the public static EditText name (after the view for it has been generated of course) from another fragment like this.
public class PageOne extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentaddress, container,
false);
EditText page_one_text = PageZero.name; //you can get that variable in any fragment now, but using the class name of that fragment to access it
return view;
}
}
Cheers. Please mark this as the correct answer if it helps you. You have quite a bit of answers here
I tried below code. Working for me
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main_explore, container, false);
ed1 = (EditText)v.findViewById(R.id.editTextTemp);
if( ed1 == null )
{
Toast.makeText(getActivity(), "ERROR UNABLE TO GET EDIT", Toast.LENGTH_LONG).show();
}
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_main_explore, container, false);
return v;
}

Populate ListView after Button Click in Fragments

So I'm trying populate a ListView in one Fragment after adding Text in an EditText field after a button click in another Fragment.
My java coding skills are pretty bad, so any code suggestions would help me a lot.
I hope this makes sense.
Here's my code.
public class FieldsActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 3;
ViewPager mPager;
MyFragmentPagerAdapter mMyFragmentPagerAdapter;
ArrayList<String>siteList = new ArrayList<String>();
CustomAdapter ca = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
mPager = (ViewPager) findViewById(R.id.fieldspager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyFragmentPagerAdapter);
mPager.setCurrentItem(1);
}
Where my ListView is.
public class AddSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.add_site, container, false);
Button addSiteButton = (Button) mRelativeLayout.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
});
ListView lv = (ListView) findViewById(android.R.id.list);
CustomAdapter ca = new CustomAdapter();
lv.setAdapter(ca);
return mRelativeLayout;
}
class CustomAdapter extends ArrayAdapter<String> {
CustomAdapter() {
super(FieldsActivity.this, android.R.layout.simple_list_item_1, siteList);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater=getLayoutInflater();
row = inflater.inflate(R.layout.list_row, null);
}
((TextView)row.findViewById(R.id.textViewId)).setText(siteList.get(position));
}
return row;
}
}
Where the Button and EditText is.
public class CreateSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.main, container, false);
final EditText siteEditText = (EditText)findViewById(R.id.siteEditText);
Button signInButton = (Button) mRelativeLayout.findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //Click this button and add to ListView in class AddSite
siteList.add(0, siteEditText.getText().toString());
ca.notifyDataSetChanged(); //(Bundle) cannot be applied
siteEditText.setText("");
mPager.setCurrentItem(1, true);
}
});
return mRelativeLayout;
}
}
While all in a FragmentPagerAdapter
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: return new SettingFields();
case 1: return new AddSite();
case 2: return new CreateSite();
}
return null;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
}
So I've commented the errors that are shown.
Hope this makes sense.
Let me know if you need to see anything else.
Thanks in advance!
Your fragments should not talk directly to each other. Instead, each fragment should report the Activity, and the Activity can decide what to do with that action.
The normal way to do this is to have a Fragment define an interface, and have the Activity implement that interface. Then there is a method that the Fragment can call, on the Activity. Then the Activity can call a method on the other Fragment to make it perform some action.
See the documentation on Fragment communication.

Categories

Resources