How to get fragment index from within itself? - android

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
}

Related

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

How to transfer the value to recylerview of one which is received from another fragment?

i have made two fragments in my app.
1st fragment (EditFrag) and 2nd fragment (ListTable). i want to transfer the value of 1st fragment(from EditText of 1st fragment) to the recyclerView of 2nd fragment.
how should i do that.....i can't find right documentation.
Thank you for your concern!
MainActivity:
public class MainActivity extends AppCompatActivity implements EditFrag.TransferValue{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListTable frag1=new ListTable();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.table_value_container,frag1,"fragment");
transaction.commit();
EditFrag frag2=new EditFrag();
FragmentManager manager1=getSupportFragmentManager();
FragmentTransaction transaction1=manager1.beginTransaction();
transaction1.add(R.id.table_container,frag2,"fragment_edit");
transaction1.commit();
}
#Override
public void sendValue(String value) {
Log.d("ashu","button is pressed");
ListTable listTable = (ListTable) getSupportFragmentManager().findFragmentById(R.id.table_value_container);
listTable.receiveValue(value);
}
}
2nd fragment(ListTable):
public class ListTable extends Fragment {
public TextView myEditText1;
private RecyclerView recyclerView;
public ListTable() {
// Required empty public constructor
}
public static ListTable newInstance(String param1, String param2) {
ListTable fragment = new ListTable();
Bundle args = new Bundle();
Log.d("ashu", "new instance is called :");
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ashu", "oncreata called by inflating: ");
View view = inflater.inflate(R.layout.fragment_list_table, container, false);
myEditText1 = (TextView) container.findViewById(R.id.table_value);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
MyAdapter a = new MyAdapter();
recyclerView.setAdapter(a);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void receiveValue(String value) {
myEditText1.setText(value);
}
public class MyAdapter extends RecyclerView.Adapter<MyDataViewHolder> {
#Override
public MyDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("ashu", "oncreateview holder of adapter ia called");
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_list_table, parent, false);
return new MyDataViewHolder(view);
}
#Override
public void onBindViewHolder(MyDataViewHolder holder, int position) {
holder.myEditText.setText("Table: " + position);
}
#Override
public int getItemCount() {
return 10;
}
}
public class MyDataViewHolder extends RecyclerView.ViewHolder {
public TextView myEditText;
public MyDataViewHolder(View itemView) {
super(itemView);
Log.d("ashu", "DAta view holder is called: ");
myEditText = (TextView) itemView.findViewById(R.id.table_value);
}
}
}
1st Fragment(EditFrag):
public class EditFrag extends Fragment {
TransferValue SendData;
EditText inputvalue;
Button click;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.edit_frag_layout, container, false);
inputvalue = (EditText) view.findViewById(R.id.edit_text);
click = (Button) view.findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String received = inputvalue.getText().toString();
SendData.sendValue(received);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SendData = (TransferValue) context;
} catch (ClassCastException e) {
Log.d("ashu", "implement the methods");
throw new ClassCastException("implemented the methods");
}
}
public interface TransferValue {
public void sendValue(String value);
}
}
create the instance of fragment2 from where want to receive the value to:
public static Fragment2 createInstance(String data) {
Fragment2 fragment = new Fragment2();
Bundle bundle = new Bundle();
bundle.putString("keyword", data);
fragment.setArguments(bundle);
return fragment;
}
and the get the data as below:
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("data");
}
You can use bundle in an order to pass data to fragment:
Example:
// Set bundle as arguments to the fragment
Bundle bundle = new Bundle();
bundle.putString(MyKey1, MyValue1);
bundle.putString(MyKey2, MyValue2);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
Inside onCreateView of fragment:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.repairer_part_details_fragment, container, false);
String value1 = getArguments().getString(MyKey1);
String value2 = getArguments().getString(MyKey2);
return view;
}
There are many ways to do that. I see your codes above, and 2 fragments loaded at the same time. I usaually use one of 2 ways below to do it.
The first solution: You can use this link using obserable pattern to communication 2 fragments.
The second solution: you can use EventBus lib for communication, it 's very simple

how to move to new fragment at on OnItemClickListener()

In my application I want to put a ListView in the first Fragment and I want to move to a new Fragment when I clicked on an item such that each item has its own details
in my code.
I implemented it to move to another Activity, but now my manager says it must go to another Fragment instead of other activity. I'm new to the Fragment world and I don't know how to do this. The manager says that I can use the list fragment but I have not found any useful code.
This my code:
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
static ProgressDialog pd ;
ViewPager mViewPager;
List<Fragment> fragments ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentOne.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentTwo.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentThree.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFour.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFive.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentSix.class.getName()));
mSectionsPagerAdapter=new SectionsPagerAdapter(super.getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
pd = new ProgressDialog(this);
mViewPager.setAdapter(mSectionsPagerAdapter);
//
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int _pos = position % 6;
return fragments.get(_pos);
}
#Override
public int getCount() {
// Show 3 total pages.
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
final String title_section4="Section4";
final String title_section5="Section5";
final String title_section6="Section6";
final String title_section1="Section1";
final String title_section2="Section2";
final String title_section3="Section3";
Locale l = Locale.getDefault();
switch (position) {
case 0:
return title_section1.toUpperCase(l);
case 1:
return title_section2.toUpperCase(l);
case 2:
return title_section3.toUpperCase(l);
case 3:
return title_section4.toUpperCase(l);
case 4:
return title_section5.toUpperCase(l);
case 5:
return title_section6.toUpperCase(l);
}
return null;
}
}
public static class FragmentOne extends Fragment {
ArrayList< String > ar;
ArrayAdapter< String > ad ;
ListView lv ;
TextView tv;
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.one, container, false);
tv = (TextView) rootView.findViewById(R.id.mywidget);
tv.setSelected(true);
ar = new ArrayList<String>();
lv = (ListView) rootView.findViewById(R.id.listView1);
for (int i = 0 ; i< 10 ; i++){
ar.add("My Item " + String.valueOf(i));
}
ad = new ArrayAdapter<String>
(getActivity().getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
ar);
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast t = Toast.makeText(getActivity(), "Message",
Toast.LENGTH_SHORT);
t.show();
Intent i = new Intent(getActivity(), tst.class);
startActivity(i);
}
});
return rootView;
}
}
public static class FragmentTwo extends Fragment {
public FragmentTwo() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.two, container, false);
return rootView;
}
}
public static class FragmentThree extends Fragment {
public FragmentThree() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.three, container, false);
return rootView;
}
}
public static class FragmentFour extends Fragment {
public FragmentFour() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.four, container, false);
return rootView;
}
}
public static class FragmentFive extends Fragment {
public FragmentFive() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.five, container, false);
return rootView;
}
}
public static class FragmentSix extends Fragment {
public FragmentSix() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.six, container, false);
return rootView;
}
}
}
You have to replace the fragment using Transaction
See here:
http://developer.android.com/guide/components/fragments.html#Example
Check the showDetails(int index) method of TitlesFragment class:
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
Use pager and give integer index to each fragment then use following code in itemclick
ViewPager pager;
pager.setCurrentItem(index, true);

How to edit a fragment and save its state?

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

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

Categories

Resources