How add and remove fragment with same button - android-fragments

I am adding a fragment with Button click. I don't want to give a separate button to remove this fragment. So how can i remove this fragment with same button.
I tried this
case R.id.BN_Tab:
Fragment fragment = new Fragment_Tab();
Fragment fragment1 = mManager.findFragmentByTag("TAB FRAGMENT");
if (!fragment.isAdded()) {
mManager.beginTransaction()
.add(R.id.Tabs_Container, fragment, "TAB FRAGMENT")
.commit();
Log.d(TAG, "Tab Fragment is Added");
} else if (fragment1 != null && fragment1.isResumed()) {
mManager.beginTransaction()
.remove(fragment)
.commit();
Log.d(TAG, "Tab Fragment is Removed()" );
}
This method continue adding same fragment and never trigger the else if() block and when i am trying to find Fragment with Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.Tabs_Container); it give NPE.

Now this simple code works for me
case R.id.BN_Tab:
Fragment fragment = mManager.findFragmentById(R.id.Tabs_Container);
if (fragment==null) {
mManager.beginTransaction()
.add(R.id.Tabs_Container, new Fragment_Tab(), "TAB FRAGMENT")
.commit();
} else {
mManager.beginTransaction()
.remove(fragment)
.commit();
}

Related

How to add error popup for empty TextField input in Scenebuilder

I am making an application using Scenebuilder with JavaFX.
I have three inputs for a TableView:
Two TextField input1, input2.
One DatePicker.
When one or more of the input fields is empty and i click on the addButton, the object is added to the TableView.
How do I show an error popup which appears whenever i click on addButton and at least one field (input1, input2) is empty ?
addButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
if ((input1.getText() != null && !input1.getText().isEmpty()) &&
(input2.getText() != null && !input2.getText().isEmpty())){
//ADD CODE TO ADD THE ITEM HERE!
} else {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Input fields empty");
alert.setContentText("Please fill all input fields");
alert.showAndWait();
}
}
});
PS : Here you can find different Alert Types depending on your needs.

add multiple fragment to cheesesquare demo

I am using an open source project(https://github.com/chrisbanes/cheesesquare) to develop my own application.
what I want is:
1.In the Home Fragment, there is a tablayout below to the toobar,and when the recycelview scroll, the Toolbar can hide, but the FloatingActionButton always stay;
2. In the Message Frgment, the is no Tab and on FloatingActionButton, only a simple blank Fragment with a Toolbar.
I try to do this in MainActivity:
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
int id = menuItem.getItemId();
if (id == R.id.nav_home) {
fragment = new HomeFragment();
} else if (id == R.id.nav_message) {
fragment = new MessageFragment();
} else if (id == R.id.nav_friends) {
fragment = new FriendsFragment();
} else if (id == R.id.nav_discussion) {
fragment = new DiscussionFragment();
}
ft.replace(R.id.viewpager, fragment);
ft.commit();
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
}
but this not work, because the tablayout stay both in HomeFragment and MessageFragment.
When I try to do change the tablayout to the layout xml of HomeFragment, I also meet some problem because the below code should write in MainActivity
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
I feel puzzled, what should I do to achieve my goals?
I try to solve the problem like this, implement the basic functions.

App Crashes On Calling Webview Loadurl method inside switch

my app contains a fragment with a webview and a edit text.i have a navigation drawer with 3 choices and use a switch condition to handle selection,on 3 selections i update the same webview with different html files using the foolowing code ..but my app crashes..
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment;
switch (position) {
case 0:
WebView wv = (WebView) findViewById(R.id.webView);
wv.loadUrl("file:///android_asset/src/web.html"); //app crashes
fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG);
if (fragment == null) {
fragment = new WebFragment();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit();
break;
case 1: fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG);
if (fragment == null) {
fragment = new WebFragment();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit();
break;
case 2: fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG);
if (fragment == null) {
fragment = new WebFragment();
}
getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit();
break;
}
}
my logcat logs http://pastebin.com/snbzASTq
please provide a workaround for this

dynamically added views inside fragment disappears on changing orientation

I am new to android application development. I have a fragment (layout of which contains one vertical linear layout). I am adding some views dynamically in the linear layout. When i change orientation to landscape from portrait the layout of fragment is recreated and all dynamically added views disappear. How can i prevent the fragment's layout from recreating?
EDIT: the code below is inside fragment. clicking on a button(say add button) dynamically adds a view in vertical linear layout but changing orientation these views disappear.
buttonAdd.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onClick(View arg0) {
methodForCheckEmail(textIn);
if(textIn.getText().toString().length() == 0) {
Toast.makeText(getActivity(), "please enter valid email", Toast.LENGTH_LONG).show();
} else if (textIn.getText().toString().length() > 0 && checkEmail == false) {
Toast.makeText(getActivity(), "please enter valid email", Toast.LENGTH_LONG).show();
} else {
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row2, null);
final TextView textOut = (TextView) addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
Button buttonRemove = (Button) addView.findViewById(R.id.remove);
arrayList.add(textIn.getText().toString());
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addView.getParent()).removeView(addView);
// textIn.setText("");
arrayList.remove(textOut.getText().toString());
}
});
textIn.setText("");
container.addView(addView);
}
//textIn.setText("");
}
});
If you change oriantation the activity will be recreated so you have to add the fragment again.
Please add code if you ask a question. You will get more help.
Use the activity lifecycle methods:
http://developer.android.com/training/basics/activity-lifecycle/index.html
Read this post:
Activity restart on rotation Android

How to get a JavaFX MenuItem to respond to a TAB KeyPress?

A JavaFX MenuItem can respond to most KeyPress events by setting an ActionEvent EventHandler. However, while the event handler does catch a KeyPress of KeyCode.ENTER, it does not catch a KeyCode.TAB KeyPress event. Apparently, some key events like TAB are handled at a deeper level. For example, the arrow keys enable traversal of the menu.
My ContextMenu is a list of completions of an email address string the user has started typing in a TextField. The users want to press the arrow keys to select the desired item, and the TAB key to execute the completion.
I can attach an event handler to the ContextMenu itself and catch the TAB keypress. But the event's Source is then the ContextMenu, and I can find no variables in the ContextMenu indicating which MenuItem was highlighted when the TAB key was pressed. MenuItem allows css style to control appearance of the menu item in focus, but it does not have any properties telling whether it is in focus or not.
I have tried futzing with the EventDispatchChain via MenuItem buildEventDispatchChain() to no avail. There seems to be no way to intercept the TAB KeyPress or otherwise determine which menu item was in focus when the TAB key was pressed.
Any suggestions?
If I get this right, you want to override the default keypressed listener to add your own response, so for that we have to find where it's applied.
To get this working, we've got to get our hands dirty with private API...
ContextMenu skin (ContextMenuSkin) uses a ContextMenuContent object, as a container with all the items. Each of these items are also in a ContextMenuContent.MenuItemContainer container.
We can override the keypressed listener on the parent container, while we can add a focusedProperty listener to the items on the items container.
Using this private API
import com.sun.javafx.scene.control.skin.ContextMenuContent;
this is working for me:
private ContextMenuContent.MenuItemContainer itemSelected=null;
#Override
public void start(Stage primaryStage) {
MenuItem cmItem1 = new MenuItem("Item 1");
cmItem1.setOnAction(e->System.out.println("Item 1"));
MenuItem cmItem2 = new MenuItem("Item 2");
cmItem2.setOnAction(e->System.out.println("Item 2"));
final ContextMenu cm = new ContextMenu(cmItem1,cmItem2);
Scene scene = new Scene(new StackPane(), 300, 250);
scene.setOnMouseClicked(t -> {
if(t.getButton()==MouseButton.SECONDARY || t.isControlDown()){
cm.show(scene.getWindow(),t.getScreenX(),t.getScreenY());
ContextMenuContent cmc= (ContextMenuContent)cm.getSkin().getNode();
cmc.setOnKeyPressed(ke->{
switch (ke.getCode()) {
case UP: break;
case DOWN: break;
case TAB: ke.consume();
if(itemSelected!=null){
itemSelected.getItem().fire();
}
cm.hide();
break;
default: break;
}
});
VBox itemsContainer = cmc.getItemsContainer();
itemsContainer.getChildren().forEach(n->{
ContextMenuContent.MenuItemContainer item=(ContextMenuContent.MenuItemContainer)n;
item.focusedProperty().addListener((obs,b,b1)->{
if(b1){
itemSelected=item;
}
});
});
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
Excellent! Thank you #jose! I ended up writing somewhat different code but
the key is using com.sun.javafx.scene.control.skin.ContextMenuContent, which provides
access to the ContextMenuContent.MenuItemContainer objects that hold the MenuItems.
In order to not break the existing UP/DOWN key behavior, I added a new handler
to the ContextMenuContent object; this handler only consumes the TAB KeyPress and
everthing else passes through to their normal handlers.
Looking at the ContextMenuContent class, I borrowed their existing method for
finding the focused item, so didn't have to add focusedProperty listeners.
Also, I'm on Java 1.7 and don't have lambdas and I use a very basic programming style.
public class MenuItemHandler_CMC <T extends Event> implements EventHandler {
public ContextMenuContent m_cmc;
public AddressCompletionMenuItemHandler_CMC(ContextMenuContent cmc){
m_cmc = cmc;
}
#Override
public void handle(Event event){
KeyEvent ke = (KeyEvent)event;
switch(ke.getCode()){
case TAB:
ke.consume();
MenuItem focused_menu_item = findFocusedMenuItem();
if(focused_menu_item != null){
focused_menu_item.fire();
}
break;
default: break;
}
}
public MenuItem findFocusedMenuItem() {
VBox items_container = m_cmc.getItemsContainer();
for (int i = 0; i < items_container.getChildren().size(); i++) {
Node n = items_container.getChildren().get(i);
if (n.isFocused()) {
ContextMenuContent.MenuItemContainer menu_item_container = (ContextMenuContent.MenuItemContainer)n;
MenuItem menu_item = menu_item_container.getItem();
return menu_item;
}
}
return null;
}
}
...Attach the additional handler
if(m_context_menu.getSkin() != null){
ContextMenuContent cmc = (ContextMenuContent)m_context_menu.getSkin().getNode();
MenuItemHandler_CMC menu_item_handler_cmc = new MenuItemHandler_CMC(cmc);
cmc.addEventHandler(KeyEvent.KEY_PRESSED, menu_item_handler_cmc);
}

Resources