Regarding moving to new screen using fragment and textview - android

I am developing an application which involves various screen for tablet. On one side I have all the tabs like notification, messages and other using fragment. When any one click on any tabs it changes the other part of screen leaving tabs unaltered. Now problem is, when I click on a tab say notification there is a message showing that " you have 3 messages",(Which is written in text view), with messages as link to that screen which shows messages. How would i achieve that when any one click on message(written in text view), it should display screen with message. In simple word how to add a link to another screen using text view.
Any help will be appreciated. Thanks in advance. My code for main activity is as follows
public class MainActivity extends ActivityGroup
{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
public void onNotificationsClick(View view)
{
setFragment(new NotificationsFragment());
}
public void onWorkListClick(View view)
{
setFragment(new WorkListFragment());
}
public void setFragment(Fragment fragment)
{
FrameLayout framelayout = (FrameLayout) findViewById(R.id.fl_container);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(framelayout.getId(), fragment).commit();
}
}

I solved it myself.
I just added in fragment_home.xml, *tv_alert_info_note text view* I added
android:clickable="true"
android:onClick="onMessageClick"
and like the same way added method "onMessageClick" in main activity class which is adding corresponding layout. that is
public void onMessageClick(View view)
{
setFragment(new TestFragment());
}
where TestFragment is fragment class.

Related

Fragments stacking on each other

I have a problem with fragments. In my xml file I have a fragment already set there, I want with the click of a button replace it with another fragment. So with my code I can replace the fragment with the one that I want on the click of the button, but the first fragment wont disappear, so I can still see it under my second fragment, the code it's this:
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment,new BlankFragment2());
fragmentTransaction.addToBackStack(null).commit();
}
});
}
}
Set a background color of the root layout of the second fragment and put clickable and focusable true in xml file. It will make disappear of the first fragment and also disable the clicks of first fragment when showing another fragment.
Remove addToBackStack(null).
That stores the Fragment and keeps it attached so that calling popBackStack() will remove the top Fragment and replace it with the previous.
correctly implementing addToBackStack will help in this case and many other
addToBackStack takes an argument which is called task record TAG , To perform a transaction later on , you can use this tag to remove back stack up to a point
For more understanding read
https://medium.com/#bherbst/managing-the-fragment-back-stack-373e87e4ff62

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 =)

Android Fragment, going back without recreating/reloading Fragment

I've seen quite a few questions on SO about Fragments and I still can't seem to figure out if what I want to do is possible, and more so if my design pattern is just flawed and I need to re-work the entire process. Basically, like most questions that have been asked, I have an ActionBar with NavigationTabs (using ActionBarSherlock), then within each Tab there is a FragementActivity and then the FragmentActivities push new Fragments when a row is selected (I'm trying to re-create an iOS Project in Android and it's just a basic Navigation based app with some tabs that can drill down into specific information). When I click the back button on the phone the previous Fragment is loaded but the Fragment re-creates itself (so the WebServices are called again for each view) and this isn't needed since the information won't change in a previous view when going backwards. So basically what I want to figure out is how do I setup my Fragments so that when I push the back button on the phone, the previous Fragment is just pulled up with the previous items already created. Below is my current code :
//This is from my FragmentActivity Class that contains the ActionBar and Tab Selection Control
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
int selectedTab = tab.getPosition();
if (selectedTab == 0) {
SalesMainScreen salesScreen = new SalesMainScreen();
ft.replace(R.id.content, salesScreen);
}
else if (selectedTab == 1) {
ClientMainScreen clientScreen = new ClientMainScreen();
ft.replace(R.id.content, clientScreen);
}.....
//This is within the ClientMainScreen Fragment Class, which handles moving to the Detail Fragment
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do something if Row is clicked
try{
String selectedClientName = clientObject.getString("ClientName");
String selectedClientID = clientObject.getString("ClientID");
String selectedValue = clientObject.getString("ClientValue");
transaction = getFragmentManager().beginTransaction();
ClientDetailScreen detailScreen = new ClientDetailScreen();
detailScreen.clientID = selectedClientID;
detailScreen.clientName = selectedClientName;
detailScreen.clientValue = selectedValue;
int currentID = ((ViewGroup)getView().getParent()).getId();
transaction.replace(currentID,detailScreen);
transaction.addToBackStack(null);
transaction.commit();
}
catch (Exception e) {
e.printStackTrace();
}
}
});....
//And then this is the Client Detail Fragment, with the method being called to Call the Web Service and create thew (since what is displayed on this screen is dependent on what is found in the Web Service
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved) {
return inflater.inflate(R.layout.clientdetailscreen, group, false);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setup Preferences File Link
this.preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
//initialize the table object
mainTable = (TableLayout)getActivity().findViewById(R.id.mainTable);
//setup the detail table
setupRelatedClientSection();
}
The Client Detail Screen can then drill down one more time, using the same method as the Client Main Screen but when I go back from that new screen to the Detail Screen the seuptRelatedClientSection() method is called again and so the entire Fragment is rebuilt when really I just want to pull up a saved version of that screen. Is this possible with my current setup, or did I approach this the wrong way?
Try using fragementTransaction.add instead of replace
I believe that you are looking for show() and hide().
I think you can still add them to the backstack.
transaction.hide(currentFragment);
transaction.show(detailScreen);
transaction.addToBackStack(null);
transaction.commit();
I didnt have my code to look at but i believe this is how it would go... Try it out unless someone else has a better way.
I have not tried the backstack with show() hide() but i believe that it takes the changes that are made before the transactions commit and will undo them if the back button is pressed. Please get back to me on this cause i am interested to know.
You also have to make sure that the detail fragment is created before you call this. Since it is based on the click of someitem then you should probably create the details fragment every time you click to make sure the correct details fragment is created.
I'm posting this answer for people who may refer this question in future.
Following code will demonstrate how to open FragmentB from FragmentA and going back to FragmentA from FragmentB (without refreshing FragmentA) by pressing back button.
public class FragmentA extends Fragment{
...
void openFragmentB(){
FragmentManager fragmentManager =
getActivity().getSupportFragmentManager();
FragmentB fragmentB = FragmentB.newInstance();
if (fragmentB.isAdded()) {
return;
} else {
fragmentManager.
beginTransaction().
add(R.id.mainContainer,fragmentB).
addToBackStack(FragmentB.TAG).
commit();
}
}
}
public class FragmentB extends Fragment{
public static final String TAG =
FragmentB.class.getSimpleName();
...
public static FragmentB newInstance(){
FragmentB fragmentB = new FragmentB();
return fragmentB;
}
#Override
public void onResume() {
super.onResume();
// add this piece of code in onResume method
this.getView().setFocusableInTouchMode(true);
this.getView().requestFocus();
}
}
In your MainActivity override onBackPressed()
class MainActivity extends Activity{
...
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
You're right, there has been a number of previous questions / documentation on the topic ;)
The documentation on Fragments, specifically the section about Transactions and Saving State, will guide you to the answer.
http://developer.android.com/guide/components/fragments.html#Transactions
http://developer.android.com/guide/components/activities.html#SavingActivityState
Android - Fragment onActivityResult avoid reloading
Fragments can have support for onSaveInstanceState but not onRestoreInstanceState, so if you want to save a reference to the table views, save them to the Bundle and you can access the saved view in your onActivityCreated method. You could also use the Fragments back stack.
This guide/tutorial has very detailed instructions/examples on the back stack and retaining fragment state.
Good luck

Display a Fragment element inside a Dialog element

In my app the same functionality should be shared between different device-oriented layouts. For handsets, I've got an activity for performing some transactions - simultaneously I've got to implement the same functionality within a popup for tablet version.
So far I've tried putting fragment into dialog both ways: statically and dynamically. When I do it statically it moans about duplicate ID and I guess this means that Fragment is already created. On the other hand when I try to implement it dynamically it says that there's no view for the fragment. I do it like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(_layoutResID);
}
#Override
public void show() {
super.show();
FragmentManager fragmentManager = ((FragmentActivity) _context).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
TabletLoginFragment loginFragment = new TabletLoginFragment();
fragmentTransaction.add(R.id.login_fragment_holder, loginFragment);
fragmentTransaction.commit();
}
Both ways I can't get it working - what would you recommend to place fragment inside of a Dialog element ?

Detect a fragment in the screen

I have a pager that contains three fragments
adapter.addFragment (new PlainColorFragment (Color.red));
adapter.addFragment (new PlainColorFragment (Color.green));
adapter.addFragment (new PlainColorFragment (Color.blue));
My question is whether it is possible to detect that fragmentation has focus or is being displayed to the user.
For example, when the green fragment is the one on screen or has focus, show a "toast" on the screen
I hope I have explained my question correctly.
thanks
Simple:
greenFragment.isVisible();
If you're looking for some kind of event, you would have to manage that manually wherever your fragment switching happens, or in your fragment class, you could execute your code in the fragment's OnHiddenChanged event (double checking, of course, that it is currently visible)
You could set an OnPageChangedListener to your ViewPager and show a different toast depending on the position.
You can create an Interface, implementing it in your Fragment and then, on parent activity, you can implement BackStackChangedListener as in example below:
public interface MyFragmentOnScreen {
public void onActiveFragment();
}
public class MyFragment extends Fragment implements MyFragmentOnScreen{
[...]
#Override
public void onActiveFragment() {
//Things you should do when your fragment becomes active
}
}
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
[...]
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
// Update your UI here.
Log.v(MainActivity.TAG, "Backstack changed");
if (getSupportFragmentManager().findFragmentById(R.id.frMain) instanceof MyFragmentOnScreen) {
((MyFragmentOnScreen) getSupportFragmentManager().findFragmentById(R.id.frMain)).onActiveFragment();
}
}
}
});
}
}
where frMain is the holder in MainActivity layout for your Fragment.

Categories

Resources