Custom ISaveHandler and IWindowCloseHandler for Eclipse e4 text editor app - eclipse

Related to question "Custom message when closing a part in Eclipse RCP 4"
I also have a Eclipse RCP 4 application with multiple editor parts (implementing MDirtyable and #Persist).
The parts are closable. When the user is closing a part there should be a custom pop-up which is asking the user if he really wants to save the part or not.
Also when the user close the appliaction a pop-up should prompt the user to close/save the dirty parts.
Basically it is intended to remove the default close eclipse e4 dialogs.
I have implemented custom ISaveHandler and IWindowCloseHandler subscribed to the application startup complete event UIEvents.UILifeCycle.APP_STARTUP_COMPLETE in the life cycle class.
Custom IWindowCloseHandler works fine (in terms of dialogs) but custom ISaveHandler is not.
ISaveHandler.save returns stackoverflow error when defined as follows:
#Override
public boolean save(MPart dirtyPart, boolean confirm) {
EPartService partService = dirtyPart.getContext().get(EPartService.class);
//Try to close the part and save the document to disc by
//calling the #Persist method
return partService.savePart(dirtyPart, confirm);
}
I have attached the complete LifeCycleManager class:
public class LifeCycleManager {
#Inject IEventBroker eventBroker;
#ProcessAdditions
public void processAdditions(MApplication application, EModelService modelService){
MWindow window =(MWindow)modelService.find("application-trimmedwindow", application);
eventBroker.subscribe(UIEvents.UILifeCycle.APP_STARTUP_COMPLETE,
new AppStartupCompleteEventHandler(window, modelService, application));
}
public class AppStartupCompleteEventHandler implements EventHandler {
private MWindow theWindow;
private MApplication app;
private ISaveHandler saveHandler;
AppStartupCompleteEventHandler(MWindow window, EModelService modelService, MApplication application){
theWindow = window;
app = application;
}
#Override
public void handleEvent(Event event) {
theWindow.getContext().set(ISaveHandler.class, new ISaveHandler() {
#Override
public boolean save(MPart dirtyPart, boolean confirm) {
System.out.println("PARTE PARA SALVAR..." + dirtyPart.getLabel());
EPartService partService = dirtyPart.getContext().get(EPartService.class);
//partService.hidePart(dirtyPart,true);
return partService.savePart(dirtyPart, confirm);
//return true;
}
#Override
public boolean saveParts(Collection<MPart> dirtyParts, boolean confirm) {
return false;
}
#Override
public Save promptToSave(MPart dirtyPart) {
return promptToSaveDialog(dirtyPart);
}
#Override
public Save[] promptToSave(Collection<MPart> dirtyParts) {
return null;
}
});
saveHandler = (ISaveHandler)theWindow.getContext().get(ISaveHandler.class);
theWindow.getContext().set(IWindowCloseHandler.class, new IWindowCloseHandler() {
#Override
public boolean close(MWindow window) {
List<MHandler> listHandlers = window.getHandlers();
System.out.println(listHandlers.size());
Shell shell = (Shell) window.getWidget();
if (MessageDialog.openConfirm(shell, "Close Nastran Editor", "Do you really want to close the entire application?")) {
Collection<EPartService> allPartServices = getAllPartServices(app);
if (containsDirtyParts(allPartServices)) {
return iterateOverDirtyParts( allPartServices);
}
else {
return true;
}
}
return false;
}});
}
private Collection<EPartService> getAllPartServices(MApplication application) {
List<EPartService> partServices = new ArrayList<EPartService>();
EModelService modelService = application.getContext().get(EModelService.class);
List<MWindow> elements = modelService.findElements(application, MWindow.class, EModelService.IN_ACTIVE_PERSPECTIVE,
new ElementMatcher(null, MWindow.class, (List<String>) null));
for (MWindow w : elements) {
if (w.isVisible() && w.isToBeRendered()) {
EPartService partService = w.getContext().get(EPartService.class);
if (partService != null) {
partServices.add(partService);
}
}
}
return partServices;
}
private boolean containsDirtyParts(Collection<EPartService> partServices) {
for (EPartService partService : partServices) {
if (!partService.getDirtyParts().isEmpty()) return true;
}
return false;
}
private boolean iterateOverDirtyParts(Collection<EPartService> allPartServices) {
for (EPartService partService : allPartServices) {
Collection<MPart> dirtyParts = partService.getDirtyParts();
for(MPart dirtyPart : dirtyParts) {
switch(saveHandler.promptToSave(dirtyPart)) {
case NO: break;
case YES:
saveHandler.save(dirtyPart, false);
break;
case CANCEL:return false;
}
}
}
return true;
}
private Save promptToSaveDialog(MPart dirtyPart) {
MessageDialog dialog = new MessageDialog( (Shell)theWindow.getWidget(), "Save file", null,
"'"+dirtyPart.getLabel()+"' has been modified. Save changes?", MessageDialog.QUESTION, new String[] { "YES", "NO", "CANCEL" }, 0);
switch (dialog.open()){
case 0: return Save.YES;
case 1: return Save.NO;
case 2: return Save.CANCEL;
default:return Save.CANCEL;
}
}
}
}///END of LifeCycleManager

The save method of ISaveHandler is called from within the EPartService savePart method so you cannot call savePart again.
Instead you should just call the #Persist method of the part. So something like:
#Override
public boolean save(final MPart dirtyPart, final boolean confirm)
{
if (confirm)
{
switch (promptToSave(dirtyPart))
{
default:
case NO:
return true;
case CANCEL:
return false;
case YES:
break;
}
}
try
{
ContextInjectionFactory.invoke(dirtyPart.getObject(), Persist.class, dirtyPart.getContext());
}
catch (final InjectionException ex)
{
// TODO ignore or log error
}
return true;
}

Related

How to combine file extension using BasicNewFileResourceWizard and initial file context while usingaWizardNewFileCreationPage at once?

I have a class for giving extension to newly created file.
public class MyNewFileWizard extends BasicNewFileResourceWizard
{
#Override
public void addPages()
{
super.addPages();
MyWizardNewFileCreationPage page = (MyWizardNewFileCreationPage )getPage("newFilePage1");
page.setFileExtension("css");
addPage(page);
}
#Override
public void init(IWorkbench workbench, IStructuredSelection currentSelection)
{
super.init(workbench, currentSelection);
setNeedsProgressMonitor(true);
}}
Also I have a class to give that created class's context
public class MyWizardNewFileCreationPage extends WizardNewFileCreationPage
{
...
#Override
protected InputStream getInitialContents()
{
//to give same strings context for every generated css file
StringBuilder sb = new StringBuilder();
sb.append("SAMPLE_CSS_FILE"); //$NON-NLS-1$
sb.append("SECTION_1"); //$NON-NLS-1$
sb.append("SECTION_1_BODY_1"); //$NON-NLS-1$
return new ByteArrayInputStream(sb.toString().getBytes());
}
plugin.xml
..
<wizard
category="ui.category"
id="ui.wizard.MyNewFileWizard"
name="Create a new app.test File"
icon="icons/project.png"
class="MyNewFileWizard"
project="false"
>
</wizard>
My goal is to create a css class with already defined context in it. So somehow combining these two class.
You can't call super.addPages because that will add the normal WizardNewFileCreationPage. You have to add only your own page:
#Override
public void addPages()
{
MyWizardNewFileCreationPage page = new MyWizardNewFileCreationPage("newFilePage1", getSelection());
page.setFileExtension("css");
addPage(page);
}
But doing this means that the standard BasicNewFileResourceWizard.performFinish won't work so you will have to override that as well:
#Override
public boolean performFinish() {
MyWizardNewFileCreationPage mainPage = (MyWizardNewFileCreationPage )getPage("newFilePage1");
IFile file = mainPage.createNewFile();
if (file == null) {
return false;
}
selectAndReveal(file);
// Open editor on new file.
IWorkbenchWindow dw = getWorkbench().getActiveWorkbenchWindow();
try {
if (dw != null) {
IWorkbenchPage page = dw.getActivePage();
if (page != null) {
IDE.openEditor(page, file, true);
}
}
} catch (final PartInitException e) {
// Show error
}
return true;
}
public class MyNewFileWizard extends BasicNewFileResourceWizard
{
WizardNewFileCreationPage mainPage;
public static final String WIZARD_ID = "ui.wizard.MyNewFileWizard";
public MyNewFileWizard()
{
super();
}
#Override
public void addPages()
{
mainPage = new WizardNewFileCreationPage("New File Page", getSelection())
{
#Override
protected InputStream getInitialContents()
{
StringBuilder sb = new StringBuilder();
sb.append("SAMPLE_README_FILE");
sb.append("SECTION_1");
sb.append("SECTION_1_BODY_1");
return new ByteArrayInputStream(sb.toString().getBytes());
}
};
mainPage.setFileExtension("css");
addPage(mainPage);
}
#Override
protected void initializeDefaultPageImageDescriptor()
{
//setDefaultPageImageDescriptor(imageHelper.getImageDescriptor("icon_48x48.png"));
}
#Override
public void init(IWorkbench workbench, IStructuredSelection currentSelection)
{
super.init(workbench, currentSelection);
setWindowTitle("New Solidity file");
setNeedsProgressMonitor(true);
}
#Override
public boolean performFinish()
{
IFile file = mainPage.createNewFile();
if (file == null) {
return false;
}
selectAndReveal(file);
// Open editor on new file.
IWorkbenchWindow dw = getWorkbench().getActiveWorkbenchWindow();
try {
if (dw != null) {
IWorkbenchPage page = dw.getActivePage();
if (page != null) {
IDE.openEditor(page, file, true);
}
}
}
catch (PartInitException e) {
//openError(dw.getShell(), "Problems opening editor", e.getMessage(), e);
}
return true;
}
}

Can you Drag and Drop a JButton copy?

Found a neat sample that really helped with illustrating how DnD works when it drags a values from a list and places it on the panel.
This sample grabs a copy of the list value.
I have since modified the sample to add a JButton. I can DnD this onto the panel but it moves it instead of making a copy.
Is there something specific as to why the JButton was moved instead of copied?
What change is required to have the button copied instead of moved?
I even tried pressing the CTRL key as I dragged the button but it still moved it instead of copying.
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.io.IOException;
import javax.swing.*;
public class TestDnD {
public static void main(String[] args) {
new TestDnD();
}
public TestDnD() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JList list;
public TestPane() {
setLayout(new BorderLayout());
list = new JList();
DefaultListModel model = new DefaultListModel();
model.addElement(new User("Shaun"));
model.addElement(new User("Andy"));
model.addElement(new User("Luke"));
model.addElement(new User("Han"));
model.addElement(new User("Liea"));
model.addElement(new User("Yoda"));
list.setModel(model);
add(new JScrollPane(list), BorderLayout.WEST);
//Without this call, the application does NOT recognize a drag is happening on the LIST.
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
list,
DnDConstants.ACTION_COPY_OR_MOVE,
new DragGestureHandler(list)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
JPanel panel = new JPanel(new GridBagLayout());
add(panel);
//This registers the Target (PANEL) where the Drop is to occur.
DropTarget dt = new DropTarget(
panel,
DnDConstants.ACTION_COPY_OR_MOVE,
new DropTargetHandler(panel), ////DropTargetHandler - is defined below
true); ///and really just implements DropTargetListener
setupButtonTest();
}
private void setupButtonTest()
{
JButton myButton = new JButton("Drag Drop Me");
add(myButton, BorderLayout.NORTH);
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
myButton,
DnDConstants.ACTION_COPY, // ACTION_COPY_OR_MOVE,
new DragGestureHandler(myButton)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
}
}
public static class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
////This Class handles the actual item or data being transferred (dragged).
public static class UserTransferable implements Transferable {
public static final DataFlavor JIMS_DATA_FLAVOR = new DataFlavor(User.class, "User");
private User user;
private JButton jbutton;
public UserTransferable(User user) {
this.user = user;
}
public UserTransferable(JButton user) {
this.jbutton = user;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
//Executed as soon as the User Object is dragged.
System.out.println("UserTransferable : getTransferDataFlavors()");
return new DataFlavor[]{JIMS_DATA_FLAVOR};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
//This is what is executed once the item is dragged into a JComponent that can accept it.
System.out.println("UserTransferable : isDataFlavorSupported()");
return JIMS_DATA_FLAVOR.equals(flavor);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
//Once a Drop is done then this method provides the data to actually drop.
System.out.println("UserTransferable : getTransferData()");
Object value = null;
if (JIMS_DATA_FLAVOR.equals(flavor)) {
if (user != null)
value = user;
else if (jbutton != null)
value = jbutton;
} else {
throw new UnsupportedFlavorException(flavor);
}
return value;
}
}
protected class DragGestureHandler implements DragGestureListener {
private JList list;
private JButton button;
public DragGestureHandler(JList list) {
this.list = list;
}
public DragGestureHandler(JButton list) {
this.button = list;
}
#Override
public void dragGestureRecognized(DragGestureEvent dge) {
//This executes once the dragging starts.
System.out.println("DragGestureHandler : dragGesturRecognized()");
if (dge.getComponent() instanceof JList)
{
Object selectedValue = list.getSelectedValue();
if (selectedValue instanceof User) {
User user = (User) selectedValue;
Transferable t = new UserTransferable(user); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
else if (dge.getComponent() instanceof JButton)
{
Object selectedValue = dge.getComponent();
if (selectedValue instanceof JButton) {
JButton jb = button;
Transferable t = new UserTransferable(jb); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
}
}
protected class DragSourceHandler implements DragSourceListener {
public void dragEnter(DragSourceDragEvent dsde) {
//This means you have entered a possible Target.
System.out.println("DragSourceHandler : DragEnter()");
}
public void dragOver(DragSourceDragEvent dsde) {
//Continually executes while the DRAG is hovering over an potential TARGET.
System.out.println("DragSourceHandler : DragOver()");
}
public void dropActionChanged(DragSourceDragEvent dsde) {
}
public void dragExit(DragSourceEvent dse) {
//Executes once the potential target has been exited.
System.out.println("DragSourceHandler : DragExit()");
}
public void dragDropEnd(DragSourceDropEvent dsde) {
//Once the mouse button is lifted to do the drop.
//Executes against any potential drop.
System.out.println("DragSourceHandler : dragDropEnd()");
}
}
protected class DropTargetHandler implements DropTargetListener {
////THESE ARE EXECUTED ONLY WHEN THE MOUSE AND DRAGGED ITEM IS OVER THE TARGET.
private JPanel panel;
public DropTargetHandler(JPanel panel) {
this.panel = panel;
}
public void dragEnter(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dragEnter()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
//This shows the outline within the TARGET to indicate it will accept the DROP.
System.out.println(" Accept...");
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
//If an item is not registered to accept a certain drop this is executed.
System.out.println(" DropTargetHandler : DragEnter() - Else");
dtde.rejectDrag();
}
}
public void dragOver(DropTargetDragEvent dtde) {
//Active while the item is being Dragged over the Target
System.out.println("DropTargetHandler : dragOver()");
}
public void dropActionChanged(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dropActionChanged()");
}
public void dragExit(DropTargetEvent dte) {
//Once the dragged item is taken out of the Target area.
System.out.println("DropTargetHandler : dragExit()");
}
public void drop(DropTargetDropEvent dtde) {
//Once the mouse button is released to do the Drop then this is executed.
System.out.println("DropTargetHandler : drop()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
Transferable t = dtde.getTransferable();
if (t.isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
try {
Object transferData = t.getTransferData(UserTransferable.JIMS_DATA_FLAVOR);
if (transferData instanceof User) {
User user = (User) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(new JLabel(user.getName()));
panel.revalidate();
panel.repaint();
}
else if (transferData instanceof JButton) {
JButton jb = (JButton) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(jb);
panel.revalidate();
panel.repaint();
}
else {
dtde.rejectDrop();
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
dtde.rejectDrop();
} catch (IOException ex) {
ex.printStackTrace();
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
}
}
}

How to reopen/prevent closing of ControlsFX LoginDialog on failed login?

In my application, the first I do is request the user to login using the controlsFX LoginDialog. If the login is successful, I display the application, however if it fails the login window will close.
I would rather the login window stay open to allow the user to attempt to login again.
public void start(Stage stage) throws Exception {
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String,String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if(success){
openDriverWindow(stage);
}else {
//Display error message
}
return null;
}
});
ld.show();
}
If the login is unsuccessful, the dialog closes - which requires the user to reopen the application.
You can use Dialog from JDK8u40 which will be released at march 2015 or use dialogs from ConrolsFX (openjfx-dialogs-1.0.2). There is a code to implement Dialog which will not be closed until authentication is not passed.
// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Login Dialog");
dialog.setHeaderText("Look, a Custom Login Dialog");
dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));
// Set the button types.
ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField username = new TextField();
username.setPromptText("Username");
PasswordField password = new PasswordField();
password.setPromptText("Password");
grid.add(new Label("Username:"), 0, 0);
grid.add(username, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(password, 1, 1);
// Enable/Disable login button depending on whether a username was entered.
Button loginButton = (Button)dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
**// Prevent closing dialog if not authenticated**
loginButton.addEventFilter(ActionEvent.ACTION, (event) -> {
if (!authenticated()) {
event.consume();
}
});
// Do some validation (using the Java 8 lambda syntax).
username.textProperty().addListener((observable, oldValue, newValue) -> {
loginButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> username.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(username.getText(), password.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
result.ifPresent(usernamePassword -> {
System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
});
this example was given from this article where you can find many useful examples
Try this:
public class Main extends Application{
private boolean login(String key, String value){
Pair loginData = new Pair<String, String>("test", "test");
if (loginData.getKey().equals(key) && loginData.getValue().equals(value)) {
return true;
}
else {
//Вывести Alert.
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
Alert alert = new Alert(Alert.AlertType.ERROR, "Вы ввели неправильное имя или пароль");
alert.setTitle("Error");
alert.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
});
return false;
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Terminal Kuban-electro");
getLogin(primaryStage);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
System.exit(0);
}
});
}
private void getLogin(Stage primaryStage){
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String, String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if (success) {
Scene scene = null;
try {
scene = new Scene(FXMLLoader.load(getClass().getClassLoader().getResource("fxml/main.fxml")));
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
}
} else {
getLogin(primaryStage);
}
return null;
}
});
ld.setHeaderText("Введите имя пользователя и пароль");
ld.setTitle("Авторизация");
ld.show();
}
public static void main(String[] args) throws MalformedURLException {
//Инициализация формы в потоке
Thread myThready = new Thread(() -> {
launch(args);
});
myThready.start();
}
}

Items does not sets disabled after first click on ListBox in Chrome

Here is my code:
listbox.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
serv.getSlotStatusesStrings(clientFactory.getWorkspaceId(), new AsyncCallback<SlotStatusGwtStruct>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(SlotStatusGwtStruct result) {
List<String> statusList = Arrays.asList(result.styleName);
int emtyCounter = 0;
boolean passFlag = false;
boolean failFlag = false;
for(String status : statusList){
if(status.equals("empty")){
emtyCounter++;
}else if(status.equals("pass")){
passFlag = true;
}else if(status.equals("fail")){
failFlag = true;
}
}
if(emtyCounter == statusList.size()){
listbox.getElement().<SelectElement>cast().getOptions().getItem(0).setDisabled(true);
}
if(passFlag == false){
listbox.getElement().<SelectElement>cast().getOptions().getItem(1).setDisabled(true);
}
if(failFlag == false){
listbox.getElement().<SelectElement>cast().getOptions().getItem(2).setDisabled(true);
}
}
});
}
});
}
In Firefox it works ok, but in Chrome browser when I click on listbox at the first time all my items are enabled (by condition they should be disabled), and after I made one more click I have the expected result.
Could yo please give me some advice how to resolve this issue.

How can i start an Activity from my sherlock ActionBar Item?

how can I start any activity from my sherlock ActionBar Item Navigation Menu?
This is my code (i've tried with toast for now and function).
public class MainActivity extends SherlockActivity implements OnNavigationListener {
private String[] pasti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pasti = getResources().getStringArray(R.array.Pasti);
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.Pasti, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
getSupportActionBar().setSubtitle("The Subtitle");
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(false);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
Toast toast=Toast.makeText(this,"Selected: " + pasti[itemPosition],Toast.LENGTH_LONG);
toast.show();
return true;
}
}
`
please help. thanks
I've solved with this code:
switch (itemPosition) {
case 1:
Intent primi = new Intent();
primi.setClass(getApplicationContext(), PrimiPiatti.class);
startActivity(primi);
break;
case 2:
break;
case 3:
break;
}
// return super.onOptionsItemSelected(itemPosition);
return true;
}
};
getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
return false;
}