Navigation drawer backstack, how to get the actionbar title to change with fragment on back click - android-fragments

so i managed to get a stock navigation drawer to work and the action bar title to change with the fragments selected. I've also managed to get the backstack working easy peasy.
What i can't figure out how to do is get the action bar title to change back with the back click. google documentations says to add a onBackStackChangedListener:
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
// Update your UI here.
}
});
but i'm at a lost where to place it? they say when i .commit to changes so i assumed it was placed after
if (id == R.id.nav_spatial_awareness) {
setTitle("Spatial Awareness");
SpatialAwareness spatialAwarenessFragment = new SpatialAwareness();
android.support.v4.app.FragmentManager spatialAwarenessManager = getSupportFragmentManager();
spatialAwarenessManager.beginTransaction()
.addToBackStack(null)
.replace(R.id.main_content_layout, spatialAwarenessFragment, spatialAwarenessFragment.getTag())
.commit();
but that didn't work, this is what i tried and all i get is red squigglies
if (id == R.id.nav_spatial_awareness) {
setTitle("Spatial Awareness");
SpatialAwareness spatialAwarenessFragment = new SpatialAwareness();
android.support.v4.app.FragmentManager spatialAwarenessManager = getSupportFragmentManager();
spatialAwarenessManager.beginTransaction()
.addToBackStack(null)
.replace(R.id.main_content_layout, spatialAwarenessFragment, spatialAwarenessFragment.getTag())
.commit();
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
setTitle("Spatial Awareness");
}
});
please help me noob
so i tried this
if (id == R.id.nav_spatial_awareness) {
setTitle("Spatial Awareness");
final SpatialAwareness spatialAwarenessFragment = new SpatialAwareness();
android.support.v4.app.FragmentManager spatialAwarenessManager = getSupportFragmentManager();
spatialAwarenessManager.beginTransaction()
.addToBackStack(null)
.replace(R.id.main_content_layout, spatialAwarenessFragment, "spatialAwarenessFragmentTag")
.commit();
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
android.app.Fragment currentBackStackFragment = getFragmentManager().findFragmentByTag("spatialAwarenessFragmentTag");
if(currentBackStackFragment instanceof SpatialAwareness){
setTitle("Spatial");
}
}
});
i gave my fragment a tag and then tried matching the instance and then changing the title, still no good :(

Yes, the solution as mentioned here is to add a FragmentManager.OnBackStackChangedListener to your activity's FragmentManager.
Here is an example from a project I worked on:
(I have a navigation drawer with 7 Fragments and the OverviewFragment is the initial one that opens when the MainActivity opens)
My MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentManager.OnBackStackChangedListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
// open the default fragment
OverviewFragment fragment = new OverviewFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment).commit();
setTitle(R.string.title_fragment_overview);
}
getSupportFragmentManager().addOnBackStackChangedListener(this);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.nav_overview:
fragment = new OverviewFragment();
break;
case R.id.nav_schedule:
fragment = new ScheduleFragment();
break;
case R.id.nav_all_tasks:
fragment = new AllTasksFragment();
break;
case R.id.nav_announcements:
fragment = new AnnouncementFragment();
break;
case R.id.nav_my_courses:
fragment = new MyCoursesFragment();
break;
case R.id.nav_map:
fragment = new MapFragment();
break;
case R.id.nav_settings:
fragment = new SettingsFragment();
break;
default:
fragment = new OverviewFragment();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment currentFragment =
fragmentManager.findFragmentById(R.id.fragment_container);
if (currentFragment instanceof OverviewFragment) {
setTitle(R.string.title_fragment_overview);
navigationView.getMenu().findItem(R.id.nav_overview).setChecked(true);
}
else if (currentFragment instanceof ScheduleFragment) {
setTitle(R.string.title_fragment_schedule);
navigationView.getMenu().findItem(R.id.nav_schedule).setChecked(true);
}
else if (currentFragment instanceof AllTasksFragment) {
setTitle(R.string.title_fragment_all_tasks);
navigationView.getMenu().findItem(R.id.nav_all_tasks).setChecked(true);
}
else if (currentFragment instanceof MyCoursesFragment) {
setTitle(R.string.title_fragment_my_courses);
navigationView.getMenu().findItem(R.id.nav_my_courses).setChecked(true);
}
else if (currentFragment instanceof AnnouncementFragment) {
setTitle(R.string.title_fragment_announcements);
navigationView.getMenu().findItem(R.id.nav_announcements).setChecked(true);
}
else if (currentFragment instanceof MapFragment) {
setTitle(R.string.title_fragment_map);
navigationView.getMenu().findItem(R.id.nav_map).setChecked(true);
}
else if (currentFragment instanceof SettingsFragment) {
setTitle(R.string.title_fragment_settings);
navigationView.getMenu().findItem(R.id.nav_settings).setChecked(true);
}
}
}
Here's the entire project: https://github.com/FCI-E-campus/fci-e-campus-android

Related

go back to previous fragment from another fragment that was started from recyclerview adapter (xamarin.android)

so I have an application that is as follows:
login page where the user enters his credentials and can access the main app if his credentials are correct. and if he checks the remember me checkbox, his username and password will be saved in shared preferences so that he can directly go to the main app in the second time.
the main app has a tabbed layout with a viewpager. in one of the tabs, which is a fragment, I use a recyclerview to display data, that I get from a database, in rows.
now in each row there is a reply button that will show details corresponding to each row when clicked. the details will be shown in a new fragment.
so the point is that I managed to replace the tab's fragment with the new fragment using this code in the recyclerview's adapter:
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
List <summary_request> summary_Requests=new List<summary_request>();
//Context context;
public readonly stores_fragment context;
public recyclerviewAdapter(stores_fragment context, List<summary_request> sum_req)
{
this.context = context;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.by_user.Text = summary_Requests[position].By;
vh.warehousename.Text = summary_Requests[position].warehousename;
vh.project.Text = summary_Requests[position].project;
vh.operations_note.Text = summary_Requests[position].destination_Note;
vh.source_Note.Text = summary_Requests[position].source_Note;
vh.stockType.Text = summary_Requests[position].stockType;
vh.requestStatus.Text = summary_Requests[position].requestStatus;
vh.reply.Click += delegate
{
summary_detail_req fragment = new summary_detail_req();
var fm = context.FragmentManager.BeginTransaction();
fm.Replace(Resource.Id.frameLayout1, fragment);
fm.AddToBackStack(null);
fm.Commit();
int nb = context.FragmentManager.BackStackEntryCount;
Toast.MakeText(context.Context, nb.ToString(), ToastLength.Long).Show();
};
}
private void Reply_Click(object sender, EventArgs e)
{
Toast.MakeText(context.Context, "reply" , ToastLength.Long).Show();
}
public override int ItemCount
{
get { return summary_Requests.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
}
}
but my context.FragmentManager.BackStackEntryCount remain zero! I don't get it. in my main activity, I am using this code for the backpress function:
stores_fragment.recyclerviewAdapter adapter;
public override void OnBackPressed()
{
string userName = pref.GetString("Username", String.Empty);
string password = pref.GetString("Password", String.Empty);
if (userName != String.Empty || password != String.Empty && adapter.context.FragmentManager.BackStackEntryCount == 0)
{
this.FinishAffinity();
}
else
base.OnBackPressed();
}
but i'm not getting what i want. this function is getting me out of the whole app.the first part of the if statement is because without it, when the I press the back button from the main activity it takes me back to the login page and I don't want that.
my question is what should I do to manage my fragments and the backpress function?
thanks in advance.
so the point is that I managed to replace the tab's fragment with the new fragment using this code in the recyclerview's adapter
According to your description, you want to open another fragment from recyclerview Button.click, if yes, please take a look the following code:
on OnBindViewHolder
int selectedindex;
// Fill in the contents of the photo card (invoked by the layout manager):
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
selectedindex =position;
PhotoViewHolder vh = holder as PhotoViewHolder;
// Set the ImageView and TextView in this ViewHolder's CardView
// from this position in the photo album:
vh.Image.SetImageResource(mPhotoAlbum[position].PhotoID);
vh.Caption.Text = mPhotoAlbum[position].Caption;
vh.btnreply.Click += Btnreply_Click;
}
To show detailed activity. MainActivity is the current activity for recyclerview.
private void Btnreply_Click(object sender, EventArgs e)
{
Showdetailed(selectedindex);
}
private void Showdetailed(int position)
{
var intent = new Intent();
intent.SetClass(MainActivity.mac, typeof(DetailsActivity));
intent.PutExtra("selectedid", position);
MainActivity.mac.StartActivity(intent);
}
The detailedactivity.cs:
public class DetailsActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
var index = Intent.Extras.GetInt("selectedid", 0);
var details = DetailsFragment.NewInstance(index); // Details
var fragmentTransaction = FragmentManager.BeginTransaction();
fragmentTransaction.Add(Android.Resource.Id.Content, details);
fragmentTransaction.Commit();
}
}
The DetailsFragment.cs:
public class DetailsFragment : Fragment
{
public int ShownPlayId => Arguments.GetInt("selectedid", 0);
public static DetailsFragment NewInstance(int index)
{
var detailsFrag = new DetailsFragment { Arguments = new Bundle() };
detailsFrag.Arguments.PutInt("selectedid", index);
return detailsFrag;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
if (container == null)
{
// Currently in a layout without a container, so no reason to create our view.
return null;
}
var scroller = new ScrollView(Activity);
var text = new TextView(Activity);
var padding = Convert.ToInt32(TypedValue.ApplyDimension(ComplexUnitType.Dip, 4, Activity.Resources.DisplayMetrics));
text.SetPadding(padding, padding, padding, padding);
text.TextSize = 24;
Photo photo =PhotoAlbum.mBuiltInPhotos[ShownPlayId];
text.Text = photo.Caption;
scroller.AddView(text);
return scroller;
}
}
About implementing fragment, you can take a look:
https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/fragmentswalkthrough/

how to implement tap gesture in webview to display html not website

I need my web view to be tappable and scrolable. Once I implement on touch the scroll doesnt work. This way i managed to get it working however now i dont know how to make the web view tappable? the ButtonPress does nothing and if i use Move then i am just scrolling
This my my render in mu droid project
class ExtendedWebViewClient : WebViewClient
{
WebView _webView;
public async override void OnPageFinished(WebView view, string url)
{
try
{
_webView = view;
if (_xwebView != null)
{
view.Settings.JavaScriptEnabled = true;
await Task.Delay(100);
string result = await _xwebView.EvaluateJavaScriptAsync("(function(){return document.body.scrollHeight;})()");
_xwebView.HeightRequest = Convert.ToDouble(result);
}
base.OnPageFinished(view, url);
}
catch (Exception ex)
{
Console.WriteLine($"{ex.Message}");
}
}
public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, IWebResourceRequest request)
{
return true;
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
_xwebView = e.NewElement as ExtendedWebView;
_webView = Control;
if (e.OldElement == null)
{
_webView.SetWebViewClient(new ExtendedWebViewClient());
}
if (e.OldElement != null)
{
Control.Touch -= ControlOnTouch;
Control.ScrollChange -= ControlOnScrollChange;
}
if (e.NewElement != null)
{
Control.Touch += ControlOnTouch;
Control.ScrollChange += ControlOnScrollChange;
}
}
private void ControlOnScrollChange(object sender, ScrollChangeEventArgs scrollChangeEventArgs)
{
if (scrollChangeEventArgs.ScrollY > 0 && scrollChangeEventArgs.OldScrollY == 0)
{
Control.Parent.RequestDisallowInterceptTouchEvent(true);
}
}
private void ControlOnTouch(object sender, Android.Views.View.TouchEventArgs e)
{
// Executing this will prevent the Scrolling to be intercepted by parent views
switch (e.Event.Action)
{
case MotionEventActions.Down:
Control.Parent.RequestDisallowInterceptTouchEvent(true);
break;
case MotionEventActions.Up:
Control.Parent.RequestDisallowInterceptTouchEvent(false);
break;
case MotionEventActions.ButtonPress:
Console.WriteLine("press");
break;
case MotionEventActions.Mask:
Console.WriteLine("mask");
break;
}
// Calling this will allow the scrolling event to be executed in the WebView
Control.OnTouchEvent(e.Event);
}
Instead of using the gesture recognizer on your webview, you can use the Focused event like following . It will been invoked when you tap the WebView .
var wb = new WebView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Source = "xxx",
};
wb.Focused += (sender, event) =>
{
//Handle your logic here!
wb.Unfocus();
};
Unfocus() is used if you want to implement your logic everytime the webview is tapped.

JavaFX Auto Scroll Table Up or Down When Dragging Rows Outside Of Viewport

I've got a table view which you can drag rows to re-position the data. The issue is getting the table view to auto scroll up or down when dragging the row above or below the records within the view port.
Any ideas how this can be achieved within JavaFX?
categoryProductsTable.setRowFactory(tv -> {
TableRow<EasyCatalogueRow> row = new TableRow<EasyCatalogueRow>();
row.setOnDragDetected(event -> {
if (!row.isEmpty()) {
Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
db.setDragView(row.snapshot(null, null));
ClipboardContent cc = new ClipboardContent();
cc.put(SERIALIZED_MIME_TYPE, new ArrayList<Integer>(categoryProductsTable.getSelectionModel().getSelectedIndices()));
db.setContent(cc);
event.consume();
}
});
row.setOnDragOver(event -> {
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
event.consume();
}
});
row.setOnDragDropped(event -> {
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
int dropIndex;
if (row.isEmpty()) {
dropIndex = categoryProductsTable.getItems().size();
} else {
dropIndex = row.getIndex();
}
ArrayList<Integer> indexes = (ArrayList<Integer>) db.getContent(SERIALIZED_MIME_TYPE);
for (int index : indexes) {
EasyCatalogueRow draggedProduct = categoryProductsTable.getItems().remove(index);
categoryProductsTable.getItems().add(dropIndex, draggedProduct);
dropIndex++;
}
event.setDropCompleted(true);
categoryProductsTable.getSelectionModel().select(null);
event.consume();
updateSortIndicies();
}
});
return row;
});
Ok, so I figured it out. Not sure it's the best way to do it but it works. Basically I added an event listener to the table view which handles the DragOver event. This event is fired whilst dragging the rows within the table view.
Essentially, whilst the drag is being performed, I work out if we need to scroll up or down or not scroll at all. This is done by working out if the items being dragged are within either the upper or lower proximity areas of the table view.
A separate thread controlled by the DragOver event listener then handles the scrolling.
public class CategoryProductsReportController extends ReportController implements Initializable {
#FXML
private TableView<EasyCatalogueRow> categoryProductsTable;
private ObservableList<EasyCatalogueRow> categoryProducts = FXCollections.observableArrayList();
public enum ScrollMode {
UP, DOWN, NONE
}
private AutoScrollableTableThread autoScrollThread = null;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
initProductTable();
}
private void initProductTable() {
categoryProductsTable.setItems(categoryProducts);
...
...
// Multi Row Drag And Drop To Allow Items To Be Re-Positioned Within
// Table
categoryProductsTable.setRowFactory(tv -> {
TableRow<EasyCatalogueRow> row = new TableRow<EasyCatalogueRow>();
row.setOnDragDetected(event -> {
if (!row.isEmpty()) {
Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
db.setDragView(row.snapshot(null, null));
ClipboardContent cc = new ClipboardContent();
cc.put(SERIALIZED_MIME_TYPE, new ArrayList<Integer>(categoryProductsTable.getSelectionModel().getSelectedIndices()));
db.setContent(cc);
event.consume();
}
});
row.setOnDragOver(event -> {
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
event.consume();
}
});
row.setOnDragDropped(event -> {
Dragboard db = event.getDragboard();
if (db.hasContent(SERIALIZED_MIME_TYPE)) {
int dropIndex;
if (row.isEmpty()) {
dropIndex = categoryProductsTable.getItems().size();
} else {
dropIndex = row.getIndex();
}
ArrayList<Integer> indexes = (ArrayList<Integer>) db.getContent(SERIALIZED_MIME_TYPE);
for (int index : indexes) {
EasyCatalogueRow draggedProduct = categoryProductsTable.getItems().remove(index);
categoryProductsTable.getItems().add(dropIndex, draggedProduct);
dropIndex++;
}
event.setDropCompleted(true);
categoryProductsTable.getSelectionModel().select(null);
event.consume();
updateSortIndicies();
}
});
return row;
});
categoryProductsTable.addEventFilter(DragEvent.DRAG_DROPPED, event -> {
if (autoScrollThread != null) {
autoScrollThread.stopScrolling();
autoScrollThread = null;
}
});
categoryProductsTable.addEventFilter(DragEvent.DRAG_OVER, event -> {
double proximity = 100;
Bounds tableBounds = categoryProductsTable.getLayoutBounds();
double dragY = event.getY();
//System.out.println(tableBounds.getMinY() + " --> " + tableBounds.getMaxY() + " --> " + dragY);
// Area At Top Of Table View. i.e Initiate Upwards Auto Scroll If
// We Detect Anything Being Dragged Above This Line.
double topYProximity = tableBounds.getMinY() + proximity;
// Area At Bottom Of Table View. i.e Initiate Downwards Auto Scroll If
// We Detect Anything Being Dragged Below This Line.
double bottomYProximity = tableBounds.getMaxY() - proximity;
// We Now Make Use Of A Thread To Scroll The Table Up Or Down If
// The Objects Being Dragged Are Within The Upper Or Lower
// Proximity Areas
if (dragY < topYProximity) {
// We Need To Scroll Up
if (autoScrollThread == null) {
autoScrollThread = new AutoScrollableTableThread(categoryProductsTable);
autoScrollThread.scrollUp();
autoScrollThread.start();
}
} else if (dragY > bottomYProximity) {
// We Need To Scroll Down
if (autoScrollThread == null) {
autoScrollThread = new AutoScrollableTableThread(categoryProductsTable);
autoScrollThread.scrollDown();
autoScrollThread.start();
}
} else {
// No Auto Scroll Required We Are Within Bounds
if (autoScrollThread != null) {
autoScrollThread.stopScrolling();
autoScrollThread = null;
}
}
});
}
}
class AutoScrollableTableThread extends Thread {
private boolean running = true;
private ScrollMode scrollMode = ScrollMode.NONE;
private ScrollBar verticalScrollBar = null;
public AutoScrollableTableThread(TableView tableView) {
super();
setDaemon(true);
verticalScrollBar = (ScrollBar) tableView.lookup(".scroll-bar:vertical");
}
#Override
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
while (running) {
Platform.runLater(() -> {
if (verticalScrollBar != null && scrollMode == ScrollMode.UP) {
verticalScrollBar.setValue(verticalScrollBar.getValue() - 0.01);
} else if (verticalScrollBar != null && scrollMode == ScrollMode.DOWN) {
verticalScrollBar.setValue(verticalScrollBar.getValue() + 0.01);
}
});
try {
sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void scrollUp() {
System.out.println("Start To Scroll Up");
scrollMode = ScrollMode.UP;
running = true;
}
public void scrollDown() {
System.out.println("Start To Scroll Down");
scrollMode = ScrollMode.DOWN;
running = true;
}
public void stopScrolling() {
System.out.println("Stop Scrolling");
running = false;
scrollMode = ScrollMode.NONE;
}
}

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.

javafx previous tabs affect newest tab

Everything works fine until I create a new tab. Then when I go to the previous and try to use any of the buttons they affect the latest tab not the one I have selected. But if I go to the latest tab it works like normal. Here is the class that I use to make my tabs. So, why is the previous tabs affecting the lastest? And how do I fix it?
public class JTab {
private javafx.scene.control.Tab tab;
private ImageView imgView;
private Image logo;
private BorderPane root;
private Button reloadButton, backButton, forwardButton;
private TextField field;
private WebView view;
private WebEngine engine;
private static JTab instance;
private JBrowser jBrowser;
private JTab(JBrowser jBrowser) {
this.jBrowser = jBrowser;
}
public static JTab getInstance(JBrowser browser) {
if(instance == null)
instance = new JTab(browser);
return instance;
}
public javafx.scene.control.Tab addTab() {
tab = new Tab();
tab.setText("New Tab");
tab.setOnClosed(event2 -> {
if(jBrowser.getTabPane().getTabs().size() == 1) {
jBrowser.getTabPane().setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
}
});
logo = new Image("unknown-document.png");
imgView = new ImageView(logo);
tab.setGraphic(imgView);
HBox hBox = new HBox(5);
hBox.setAlignment(Pos.CENTER);
reloadButton = new Button("Reload");
backButton = new Button("<");
forwardButton = new Button(">");
reloadButton.setOnAction(event1 -> engine.reload());
backButton.setOnAction(event1 -> loadData(goBack()));
forwardButton.setOnAction(event1 -> loadData(goForward()));
//The TextField for entering web addresses.
field = new TextField("Enter URL");
field.setPrefColumnCount(50); //make the field at least 50 columns wide.
field.focusedProperty().addListener((ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) -> { //When click on field entire thing selected
Platform.runLater(() -> {
if (field.isFocused() && !field.getText().isEmpty()) {
field.selectAll();
}
});
});
field.setOnKeyPressed(event -> { //When ENTER is pressed it will load page
if (event.getCode() == KeyCode.ENTER) {
if (!field.getText().isEmpty()) {
loadData(field.getText());
}
}
});
//Add all out navigation nodes to the vbox.
hBox.getChildren().addAll(backButton, forwardButton, reloadButton, field);
view = new WebView();
engine = view.getEngine();
engine.setJavaScriptEnabled(true);
engine.getLoadWorker().stateProperty().addListener(
(ov, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
tab.setText(getTitle());
//TODO setGraphic
}
});
loadData("google.com");
root = new BorderPane();
root.setPrefSize(1024, 768);
root.setTop(hBox);
root.setCenter(view);
tab.setContent(root);
return tab;
}
public void loadData(String URL) {
if(!URL.startsWith("http://")) {
URL = "http://" + URL;
}
field.setText(URL);
tab.setText(URL);
engine.load(URL);
}
private String getTitle() {
Document doc = engine.getDocument();
NodeList heads = doc.getElementsByTagName("head");
String titleText = engine.getLocation() ; // use location if page does not define a title
if (heads.getLength() > 0) {
Element head = (Element)heads.item(0);
NodeList titles = head.getElementsByTagName("title");
if (titles.getLength() > 0) {
Node title = titles.item(0);
titleText = title.getTextContent();
}
}
return titleText;
}
private String goBack() {
final WebHistory history = engine.getHistory();
ObservableList<WebHistory.Entry> entryList = history.getEntries();
int currentIndex=history.getCurrentIndex();
Platform.runLater(() -> history.go(-1));
return entryList.get(currentIndex>0?currentIndex-1:currentIndex).getUrl();
}
private String goForward() {
final WebHistory history = engine.getHistory();
ObservableList<WebHistory.Entry> entryList=history.getEntries();
int currentIndex=history.getCurrentIndex();
Platform.runLater(() -> history.go(1));
return entryList.get(currentIndex<entryList.size()-1?currentIndex+1:currentIndex).getUrl();
}
}
Remove getInstance(jBrowser) method
Make the constructor public.
Then to add a tab to a tabPane do
tabPane.getTabs().add(new JTab(jBrowser).addTab());

Resources