how to keep button text the same when switching fragments - android

Hi I have a program with several fragments in one activity. The menu fragment lets the user switch to one of the other fragment layouts. I have many buttons on the menu fragment layout that change text when pressed.
I want this text to remain the same when I navigate back from one of the other fragments but it goes back to its default text while the spinners hold their position. Since the fragment only stopped not destroyed I thought the buttons would hold there text? Sorry if it's something obvious, I'm new to programming.
here is some out my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View rootView = inflater.inflate(R.layout.options_menu, container, false);
Channel0 = (Button)rootView.findViewById(R.id.Channel0);
OpenChannel0 = (Button)rootView.findViewById(R.id.Channel0Open);
OpenChannel0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ( OpenChannel0.getText().equals("Open") )
{
Channel0Spinner.setEnabled(false);
OpenChannel0.setText("Close");
String text = Channel0Spinner.getSelectedItem().toString();
Channel0.setText("Channel 0 ("+ text +")");
else
{
Channel0Spinner.setEnabled(true);
OpenChannel0.setText("Open");
}
}
});
Channel0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
f = new Channel0frag();
FragmentTransaction frag = getFragmentManager().beginTransaction();
frag.replace(R.id.container, f);
frag.addToBackStack(null);
frag.commit();
}
}
});
So when I navigate back from Channel0frag, I want buttons Channel0 and OpenChannel0 to keep whatever text is set.
UPDATE:
When I enter the following code in the onResume method, it still outputs the original button text when I navigate back from another fragment even though the spinner does not lose its position. Why is Channel0 button text not getting assigned to the text displayed in the spinner?
String text = Channel0Spinner.getSelectedItem().toString();
Channel0.setText("Channel 0 ("+ text +")");

maintain global variable in your application class and override onResume on fragment class.

I Created a boolean variable and set it to true then OpenChannel0 button text was "Open" and checked the state of it and set the button text in onResume. For OpenChannel0 I used Shared Preferences to save the text state as there was several different text states for this button.

Related

How to make changes in widget in parent activity based on the logic written in fragment

As an exercise i am writing a simple Ebook reader app. This has only 1 Main Activity with 3 widgets on it, 2 buttons (Previous, Next) and one Fragment container(I have used Frame Layout). All pages are different fragments that I have created that will go inside the container, and these fragments have only 1 scrollable text view that will only display text. when "next" button is pressed it should go to page2(fragment2) and when previous is pressed it should go back(previous fragment).
My problem is I don't want the "previous" button to show up on the initial screen (page1) and similarly the "next" button should not be observed on the last page.
The approach i tried was, in my fragment1(page1) class, i wrote an if condition like,
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragmentpage1,container,false);
textView1=(TextView)view.findViewById(R.id.tview);
**View listView = getActivity().findViewById(R.id.previous);**
textView1.setText(R.string.page1);
if (textView1.isEnabled()){
listView.setVisibility(View.INVISIBLE);
}
return view;
}
I am checking if textview1(the first fragment) is present or not , if yes then hide the previous button on the Main Activity. This works but it completely hides the previous button even when i go to page2. I tried all possible "is" options but none of them are giving me the results I want.
One workaround that i found was to add "setvisibility" of previous button to all fragments, so on fragment1 it is invisible and then on fragment2 i changed that to visible. But that becomes lengthy if there are 100s of fragments(pages).
Please provide me with a simple solution, I am new to Android.
Below is my Main Activity code:(Do let me know if any changes needs to be done to make code more clean)
public class MainActivity extends FragmentActivity {
Fragment fragment;
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft;
private static Button next;
private static Button previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
next=(Button)findViewById(R.id.next);
previous=(Button)findViewById(R.id.previous);
create();
}
public void create(){
fragment= new FragmentPage1();
ft= fm.beginTransaction();
ft.add(container,fragment);
ft.commit();
}
public void next(View view){
fragment= new FragmentPage2();
ft= fm.beginTransaction();
ft.replace(container,fragment);
ft.commit();
}
}
Maybe you can try to use the getItem() method in FragmentPagerAdapter class.
Try to disable or enable your buttons using the switch case. Hope this can help =)

Tabbed activity(fragment) to activity navigation using onClick

I have a Tabbed activity with 3 tabs and each tab has its own fragment.
there's a button inside the first tab which i want to click and navigate to another Tabbed activity (or any activity which has a fragment). How do I accomplish this ? I am trying to click on a button and open a new activity but i am unable to do so. I would really appreciate if i get some headers as I'm learning android. Here's a link to my fragment class for reference.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tutorials,container, false);
Button button1 = (Button) view.findViewById(R.id.introbtn1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent tutorial = new Intent(getActivity(), TutorialIntroduction.class);
startActivity(tutorial);
//Tried to create a toast to check if the button works but it doesn't
//Toast.makeText(getActivity(), "button is clicked!", Toast.LENGTH_LONG).show();
}
});
return view;
}
In your fragment create a ViewPager variable and a setter method for it that is called when the fragment is created in your activity(its better to do this in constructor but it says you require it empty). Then in the onClick
ViewPager.setCurrentItem(FragmentPostion)
FragmentPostion is the int of which page you want to switch to, in your case from 0-2 (or 1-3 can't remember, try both haha).

Checkbox's isChecked getting NullPointerException

I have an activity with 6 fragments(Swipe disabled). For each fragment I have 2 button( next and previous) which move to 1 fragment next and previous perfectly. I have 2 checkboxes which I need to check if they are checked or not before migrating to next activity. But I get null pointer because checkboxes are initialized in onCreateView Method but the fragment is loaded already due to viewpager. How can I check if checkboxes are checked or not?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_step6, container, false);
cb1 = (CheckBox)v.findViewById(R.id.cb1);
next = (Button)v.findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(cb1.isChecked())
return true;
}
});
}
ViewPager will preload fragments for you and it's not going to remove old fragments from memory immediately. I do not think the problem is that the view is gone when the user clicks on the next button.
Check your layout file and make sure you have a checkbox in res/layout/fragment_step6.xml with the ID cb1.
pager.setOffscreenPageLimit(6);//6 = to the number you included in your question.
this will tell viewpager to retain your fragments while scrolling pages so you dont lost your state.

Place button just on the last page of a viewPager

I'm trying to have a button appear on the last page of a viewPager (which contains images in fragments). In these fragments, I'm creating a button that is invisible until the last page is shown. So far, I've achieved this behavior, but I'm having a bug where in page 2 the button appears, even though I'm "showing" (with setVisibility(View.VISIBLE)) the button only when the current page is greater or equal than 3 (there are 5 pages total, and also, greater or equal than 3 because the viewPager.getCurrentItem() behaves oddly and won't count the last or first page as an index).
My custom fragment's onCreateView() looks like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.imageview, container, false);
ivImage = (ImageView) root.findViewById(R.id.ivImageView);
btn_register = (Button) root.findViewById(R.id.button_register);
if( ((WelcomeActivity) this.getActivity()).test()>=3){
btn_register.setVisibility(View.VISIBLE);
}
setImageInViewPager();
return root;
}
In my main activity, the test() method simply returns the current page the viewPager is in:
public int test(){
return(viewPage.getCurrentItem());
}
How could I better detect the last page of a viewpager and use it so that I only display the button when the user is in the last page of the viewpager? thanks!
EDIT:
Here is a video of the problem.
HEre are the contents of my src folder: WelcomeActivity.java, FragmentPagerAdapter.java, Images.java, FragmentImageView.java.
In onPageSelected(), check the position : if(position==5) then show the button. Here I used
5 because you mention that there are 5 pages.
#Override
public void onPageSelected(int position) {
if(position == 5)
btn_register.setVisibility(View.VISIBLE);
}
Try this hope it will help you :)
You need to somehow tie the count of fragments to the individual fragments. So that each fragment knows its index. Can you add your code on how and when you are creating/adding the fragments to the view-pager?
Basing on that you can add a param to the arguments bundle while initialising the fragment there by fragment knows it's index in the view-pager.
Or else try this,
private int mCurrentPageSelected;
// In your activity
#Override
public void onPageSelected(int position) {
mCurrentPageSelected = position;
}
public int getSelectedPagePosition(){
return mCurrentPageSelected;
}
// In your fragment
public void onAttach(){
Log.d(TAG, "Fragment attached and current selected position is" + etActivity().getSelectedPagePosition());
if(getActivity().getSelectedPagePosition() >= 3){
// show the btn
btn_register.setVisibility(View.VISIBLE);
}else{
//hide the button
btn_register.setVisibility(View.GONE);
}
}

After screen orientation change the dialogFragment appears apparently without any call

here there is part of the Activity where the screen orientation change:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
et.setOnLongClickListener(new View.OnLongClickListener()
{
#Override
public boolean onLongClick(View v)
{
Fragment1 dialogFragment = new Fragment1();
dialogFragment.show(getFragmentManager(), null);
dialogFragment.setTextDialog(et.getText().toString());
return true;
}
});
}
Apparentely it seems that the dialog that will appear inside the DialogFragment should appear just after the onLongClick over the editText
(I know that when the screen orientation change the Activity is restarted, but it shouldn't start normally like the first time that is created?)
My problem:
when I open at least once the dialog and I close it, after the screen orientation change I have the dialog displayed again on the screen, like if I long-Clicked the editText.
I don't absolutely know why this happens.
I attach also the structure of dialog fragment:
public Dialog onCreateDialog(Bundle savedInstanceState)
{
final Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LayoutInflater adbInflater = LayoutInflater.from(getActivity());
View eulaLayout = adbInflater.inflate(R.layout.dialog_crypt, null);
Button btn_OK = (Button) eulaLayout.findViewById(R.id.btnOK);
dialog.setContentView(eulaLayout);
final EditText et = (EditText)eulaLayout.findViewById(R.id.editText2);
et.setText(textDialog);
if(et.length()>0)
{
et.setText(et.getText().toString() + " ");
}
et.setSelection(et.length());
btn_OK.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
textDialog = et.getText().toString();
((Main)getActivity()).setTextOnEditText(textDialog);
dialog.dismiss();
}
});
return dialog;
}
Thanks so much for the help.
Try removing the dialog from stack using fragment manager instead of just dismissing it.
getFragmentManager().beginTransaction().remove(dialogFragment.this).commit();
By the way, instead of just using a Fragment for your dialog, you should use DialogFragment itself. Checkout: DialogFragment
Also, don't ever call your activity methods like this ( ((Main)getActivity()).setTextOnEditText(textDialog);
unless your fragment is a static inner class. Instead, create an interface to talk between fragments and activity.
When screen changes orientation, it calls onSaveInstanceState method, and it saves the state in the Bundle object including the stack. If you dismiss the dialog without clearing this stack, it will then show the dialog when you rotate the phone since this is in the saveInstanceState bundle.
You must clear dialog off the stack with:
getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
if you use support library for dialog fragment, or
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
When a config change (like rotation) occurs the old Fragment isn't destroyed - it just adds itself back to the Activity when it's recreated (android retains fragments by default). So if you have your DialogFragment shown before rotation, it will instantly show up after rotation.

Categories

Resources