How to add a JDialog in to desktop pane or just call from an internal frame - modal-dialog

I am working on a project that uses MDI form in java. I have created a frame and then added a desktop pane to it. My project uses lot of internal frames. Also those internal frames require to show custom dialogs that i have created on my own. for it to be clear, i say, one jdialog has a table asking the user to select one row. but the problem is when i call the jdialog from the internal frame (with modality=true), the dialog is show on the top of main frame and not just on the top of internal frame. This makes it impossible to minimize the window when the jdialog is showing.
In my view there are 2 possible solutions (which may not possible!!).. Either the jdialog should be shown inside the dektop pane or i should create an internal frame instead of jdialog and make it appear to be modal to the parent internal frame. i.e, when i want to show the dialog, i may disable the internal frame and set the form unable to focus and then show a new internal frame on the top of this internal frame. I have been searching the forums for weeks.. but i couldn't find an answer. I hope you would have a solution. Thanks in advance, sir.

I also had the same problem, while working on a java project that works quite fine in java 6 but shown the same problem when changed to java7.
I found a solution.
I added a
dialog.setVisible(false) followed by a dialog.setVisible(true).
Then the dialog is responding to keyboard.

I am also working on an MDI app that uses a lof internal frames which show custom dialogs. I make my dialogs non-modal so that the internal frames can be iconified and/or the whole desktoppane can be minimized while the dialogs remain visible.
If you absolutely need modal behavior (i.e., you want to require the user to interact with a dialog before doing anything else) perhaps you can leave the dialog modeless but code in de facto modality.
Also, have you looked at the behavior of
setModalityType(java.awt.Dialog.ModalityType.DOCUMENT_MODAL);
?

Wow!! I got the answer from webbyt... Just avoid using internal frames.. try using the class ModalityInternalFrame (subclass of JinternalFrame).. and everything works fine.. Here is the class
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
/**
* An extended
* <code>JInternalFrame</code> that provides modality in a child/parent
* hierarchy
*
* #author webbyit
*/
public class ModalityInternalFrame extends JInternalFrame {
protected JDesktopPane desktopPane;
protected JComponent parent;
protected ModalityInternalFrame childFrame;
protected JComponent focusOwner;
private boolean wasCloseable;
public ModalityInternalFrame() {
init(); // here to allow netbeans to use class in gui builder
}
public ModalityInternalFrame(JComponent parent) {
this(parent, null);
}
public ModalityInternalFrame(JComponent parent, String title) {
this(parent, title, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable) {
this(parent, title, resizable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable) {
this(parent, title, resizable, closeable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable,
boolean maximizable) {
this(parent, title, resizable, closeable, maximizable, false);
}
public ModalityInternalFrame(JComponent parent, String title, boolean resizable, boolean closeable,
boolean maximizable,
boolean iconifiable) {
super(title, resizable, closeable, maximizable, iconifiable);
setParentFrame(parent);
//setFocusTraversalKeysEnabled(false);
if (parent != null && parent instanceof ModalityInternalFrame) {
((ModalityInternalFrame) parent).setChildFrame(ModalityInternalFrame.this);
/*
* set focus to the new frame and show the frame Code added by Jasir
*/
try {
((ModalityInternalFrame) parent).setSelected(false);
setSelected(true);
setVisible(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(ModalityInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Add glass pane
ModalityInternalGlassPane glassPane = new ModalityInternalGlassPane(this);
setGlassPane(glassPane);
// Add frame listeners
addFrameListener();
// Add frame veto listenr
addFrameVetoListener();
init();
// calculate size and position
}
private void setParentFrame(JComponent parent) {
desktopPane = JOptionPane.getDesktopPaneForComponent(parent);
this.parent = parent == null ? JOptionPane.getDesktopPaneForComponent(parent) : parent; // default to desktop if no parent given
}
public JComponent getParentFrame() {
return parent;
}
public void setChildFrame(ModalityInternalFrame childFrame) {
this.childFrame = childFrame;
}
public ModalityInternalFrame getChildFrame() {
return childFrame;
}
public boolean hasChildFrame() {
return (childFrame != null);
}
protected void addFrameVetoListener() {
addVetoableChangeListener(new VetoableChangeListener() {
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
if (evt.getPropertyName().equals(JInternalFrame.IS_SELECTED_PROPERTY)
&& evt.getNewValue().equals(Boolean.TRUE)) {
if (hasChildFrame()) {
//childFrame.setSelected(true);
if (childFrame.isIcon()) {
childFrame.setIcon(false);
}
throw new PropertyVetoException("no!", evt);
}
}
}
});
}
/**
* Method to control the display of the glass pane, dependant on the frame
* being active or not
*/
protected synchronized void addFrameListener() {
addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameActivated(InternalFrameEvent e) {
if (hasChildFrame() == true) {
getGlassPane().setVisible(true);
grabFocus();
} else {
getGlassPane().setVisible(false);
}
}
#Override
public void internalFrameOpened(InternalFrameEvent e) {
getGlassPane().setVisible(false);
try {
setSelected(true);
} catch (PropertyVetoException ex) {
Logger.getLogger(ModalityInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void internalFrameClosing(InternalFrameEvent e) {
if (parent != null && parent instanceof ModalityInternalFrame) {
((ModalityInternalFrame) parent).childClosing();
}
}
});
}
/**
* Method to handle child frame closing and make this frame available for
* user input again with no glass pane visible
*/
protected void childClosing() {
setClosable(wasCloseable);
getGlassPane().setVisible(false);
if (focusOwner != null) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
moveToFront();
setSelected(true);
focusOwner.grabFocus();
} catch (PropertyVetoException ex) {
}
}
});
focusOwner.grabFocus();
}
getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
setChildFrame(null);
getDesktopPane().setSelectedFrame(this);
System.out.println(getDesktopPane().getSelectedFrame());
}
/*
* Method to handle child opening and becoming visible.
*/
protected void childOpening() {
// record the present focused component
wasCloseable = isClosable();
setClosable(false);
focusOwner = (JComponent) getMostRecentFocusOwner();
grabFocus();
getGlassPane().setVisible(true);
getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
#Override
public void show() {
if (parent != null && parent instanceof ModalityInternalFrame) {
// Need to inform parent its about to lose its focus due
// to child opening
((ModalityInternalFrame) parent).childOpening();
}
calculateBounds();
super.show();
}
protected void init() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 394, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 274, Short.MAX_VALUE));
pack();
}
public void calculateBounds() {
Dimension frameSize = getPreferredSize();
Dimension parentSize = new Dimension();
Dimension rootSize = new Dimension(); // size of desktop
Point frameCoord = new Point();
if (desktopPane != null) {
rootSize = desktopPane.getSize(); // size of desktop
frameCoord = SwingUtilities.convertPoint(parent, 0, 0, desktopPane);
parentSize = parent.getSize();
}
//setBounds((rootSize.width - frameSize.width) / 2, (rootSize.height - frameSize.height) / 2, frameSize.width, frameSize.height);
// We want dialog centered relative to its parent component
int x = (parentSize.width - frameSize.width) / 2 + frameCoord.x;
int y = (parentSize.height - frameSize.height) / 2 + frameCoord.y;
// If possible, dialog should be fully visible
int ovrx = x + frameSize.width - rootSize.width;
int ovry = y + frameSize.height - rootSize.height;
x = Math.max((ovrx > 0 ? x - ovrx : x), 0);
y = Math.max((ovry > 0 ? y - ovry : y), 0);
setBounds(x, y, frameSize.width, frameSize.height);
}
/**
* Glass pane to overlay. Listens for mouse clicks and sets selected on
* associated modal frame. Also if modal frame has no children make class
* pane invisible
*/
class ModalityInternalGlassPane extends JComponent {
private ModalityInternalFrame modalFrame;
public ModalityInternalGlassPane(ModalityInternalFrame frame) {
modalFrame = frame;
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (modalFrame.isSelected() == false) {
try {
modalFrame.setSelected(true);
if (modalFrame.hasChildFrame() == false) {
setVisible(false);
}
} catch (PropertyVetoException e1) {
//e1.printStackTrace();
}
}
}
});
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(new Color(255, 255, 255, 100));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
But there are some problems still with focus and something else..

Related

How to remove "no data" labels from empty nodes in GWT?

I have a widget that inherits from CellTree. If the node not have the child elements, this node can be opened and shows "no data" label.
I'd like to see nodes without child's displayed as empty.
That's how I fill the tree. My DictionaryTreeDataProvider class (relevant part):
public class DictionaryTreeDataProvider extends ListDataProvider<MValue> {
private final DictionariesServiceAsync service = GWT.create(DictionariesService.class);
...
#Override
public void onRangeChanged(HasData<MValue> result) {
service.queryDictionaryValues(range, query, new AsyncCallback<SubsetResult<MValue>>() {
#Override
public void onFailure(Throwable t) {
}
#Override
public void onSuccess(SubsetResult<MValue> result) {
getList().clear();
for (MValue value : result.items) {
getList().add(value);
}
}
});
}
}
On the server side I make EJB call which fills SubsetResult.
I found that this problem fixed in version of GWT-2.5.0-rc2 (see https://groups.google.com/forum/#!topic/google-web-toolkit/d-rFUmyHTT4).
Now everything is OK, thanks to #moutellou.
I did as he suggested:
...
#Override
public void onSuccess(SubsetResult<MValue> result) {
if (result.length == 0) {
updateRowCount(-1, true);
return;
} else {
for (MValue value : result.items) {
// some checks here
getList().add(value);
}
}
}
...
Some alternative solution. Can be defined interface that extends the interface CellTree.Resources.
In this interface must specify the path to the CSS, which override the desired style.
Interface CellTree.Resources:
public class CellTree extends AbstractCellTree implements HasAnimation,
Focusable {
...
/**
* A ClientBundle that provides images for this widget.
*/
public interface Resources extends ClientBundle {
/**
* An image indicating a closed branch.
*/
#ImageOptions(flipRtl = true)
#Source("cellTreeClosedArrow.png")
ImageResource cellTreeClosedItem();
/**
* An image indicating that a node is loading.
*/
#ImageOptions(flipRtl = true)
ImageResource cellTreeLoading();
/**
* An image indicating an open branch.
*/
#ImageOptions(flipRtl = true)
#Source("cellTreeOpenArrow.png")
ImageResource cellTreeOpenItem();
/**
* The background used for selected items.
*/
#ImageOptions(repeatStyle = RepeatStyle.Horizontal, flipRtl = true)
ImageResource cellTreeSelectedBackground();
/**
* The styles used in this widget.
*/
#Source(Style.DEFAULT_CSS)
Style cellTreeStyle();
}
...
}
Interface CustomCellTreeResources, based on CellTree.Resources:
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.user.cellview.client.CellTree;
public interface CustomCellTreeResources extends CellTree.Resources {
static final String STYLE_PATH = "components/common/client/static/custom-cell-tree.css";
#Override
#ClientBundle.Source({CellTree.Style.DEFAULT_CSS, STYLE_PATH})
CellTree.Style cellTreeStyle();
}
Overriding rule:
.cellTreeEmptyMessage {
display: none;
}
Create an instance:
private final static CellTree.Resources customCellTreeResources =
GWT.create(CustomCellTreeResources.class);
And next need to explicitly pass customCellTreeResources to the CellTree class constructor.
Message is not displayed more.
Mandatory: before filing the list, ie, before clicking on a node, the list should be cleaned( getList().clear();):
#Override
public void onRangeChanged(HasData<MValue> result) {
service.queryDictionaryValues(range, query,
new AsyncCallback<SubsetResult<MValue>>() {
#Override
public void onFailure(Throwable t) {}
#Override
public void onSuccess(SubsetResult<MValue> result) {
getList().clear();
for (MValue value : result.items) {
getList().add(value);
}
}
});
}
This is how I removed the no data label in my DataProvider
//Fetch children
int size = children.size();
if (size == 0) {
updateRowCount(-1, true); //Method called on AsyncDataProvider
return;
}
In the TreeViewModel, make sure that the isLeaf method returns true if the argument value has no children. Example:
#Override
public boolean isLeaf(Object value) {
if (value instanceof DepartmentDto) {
DepartmentDto department = (DepartmentDto) value;
return department.getEmployees().isEmpty();
} else if (value instanceof EmployeeDto) {
return true;
} else {
return false;
}
}
In this case, a department should declare itself as a leaf only if it has no employees, an employee will declare itself as a leaf, and default to false.
Note that value many also be an internal GWT node. In this example, it might not necessarily be just DepartmentDto and EmployeeDto.

GWT - button inside v3 google maps infowindow

I am trying to figure out how to propagate events for components inside google maps InfoWindow.
I create anchor or a button and want to handle click event on any of those.
I have found solutions described here
and
here
but those both are using google maps wrappers for gwt.
I would like to avoid those libraries.
QUESTION:
Do you know any way how can I propagate those events from info window to some GWT panel which wraps google maps?
Based on code found here:
http://gwt-maps3.googlecode.com/svn/trunk/src/com/googlecode/maps3/client/
I have created this class that solves problem with using no external library (you have to take Only InfoWindowJSO source from link given)
And then instead passing InnerHtml as string to setContent... you just pass Widget element.
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Widget;
public class InfoWindow
{
static class FakePanel extends ComplexPanel
{
public FakePanel(Widget w)
{
w.removeFromParent();
getChildren().add(w);
adopt(w);
}
#Override
public boolean isAttached()
{
return true;
}
public void detachWidget()
{
this.remove(0);
}
}
/** */
InfoWindowJSO jso;
/** If we have a widget, this will exist so we can detach later */
FakePanel widgetAttacher;
/** Keep track of this so we can get it again later */
Widget widgetContent;
/** */
public InfoWindow()
{
this.jso = InfoWindowJSO.newInstance();
}
/** */
public InfoWindow(InfoWindowOptions opts)
{
this.jso = InfoWindowJSO.newInstance(opts);
}
/** Detaches the handler and closes */
public void close()
{
this.detachWidget();
this.jso.close();
}
/** Detaches the content widget, if it exists */
private void detachWidget()
{
if (this.widgetAttacher != null)
{
this.widgetAttacher.detachWidget();
this.widgetAttacher = null;
}
}
/** */
public void open(JavaScriptObject map)
{
this.jso.open(map);
}
public void open(JavaScriptObject map, JavaScriptObject marker)
{
this.jso.open(map, marker);
}
/** */
public void setOptions(InfoWindowOptions value)
{
this.jso.setOptions(value);
}
/** */
public void setContent(String value)
{
this.widgetContent = null;
this.detachWidget();
this.jso.setContent(value);
}
/** */
public void setContent(Element value)
{
this.widgetContent = null;
this.detachWidget();
this.jso.setContent(value);
}
/** */
public void setContent(Widget value)
{
this.widgetContent = value;
this.detachWidget();
this.jso.setContent(value.getElement());
if (this.widgetAttacher == null)
{
// Add a hook for the close button click
this.jso.addListener("closeclick", new Runnable() {
#Override
public void run()
{
detachWidget();
}
});
this.widgetAttacher = new FakePanel(value);
}
else if (this.widgetAttacher.getWidget(0) != value)
{
this.widgetAttacher.detachWidget();
this.widgetAttacher = new FakePanel(value);
}
}
/** #return the widget, if a widget was set */
public Widget getContentWidget()
{
return this.widgetContent;
}
/** */
public JavaScriptObject getPosition()
{
return this.jso.getPosition();
}
/** */
public void setPosition(JavaScriptObject value)
{
this.jso.setPosition(value);
}
/** */
public int getZIndex()
{
return this.jso.getZIndex();
}
/** */
public void setZIndex(int value)
{
this.jso.setZIndex(value);
}
/** */
public void addListener(String whichEvent, Runnable handler)
{
this.jso.addListener(whichEvent, handler);
}
}
A. Browser events bubble all the way to the top of the DOM tree. You can attach your click handlers to a widget that is parent to both the maps InfoWindow and your widget. Then, when a user clicks on your button, you need to check for the source of event to make sure it came from your button.
public void onClick(final ClickEvent event) {
Element e = Element.as(event.getNativeEvent().getEventTarget());
// check if e is your button
}
B. You can create a regular GWT button, attach a ClickHandler to it. Do not put it inside the InfoWindow: place it on top it using absolute positioning and a higher z-index.
I use the static value nextAnchorId to uniquely generate IDs for each InfoWindow, and when the InfoWindow is ready (usually when you call infoWindow.open(map);), I get the anchor by element ID and add my click handler to it. This is kind of what Manolo is doing, but this implementation doesn't require gwtquery, which means that I can run my code in Super Dev Mode.
private static int nextAnchorId = 1;
public InfoWindow makeInfo() {
InfoWindowOptions infoWindowOptions = InfoWindowOptions.create();
FlowPanel infoContentWidget = new FlowPanel();
final String theAnchorId_str = "theAnchor" + nextAnchorId;
HTML theAnchor = new HTML("<a id=\"" + theAnchorId_str + "\">Click me!</a>");
infoContentWidget.add(theAnchor);
infoWindowOptions.setContent(infoContentWidget.getElement());
InfoWindow infoWindow = InfoWindow.create(infoWindowOptions);
infoWindow.addDomReadyListenerOnce(new InfoWindow.DomReadyHandler() {
#Override
public void handle() {
com.google.gwt.user.client.Element muffinButton = (com.google.gwt.user.client.Element) Document.get().getElementById(theAnchorId_str);
DOM.sinkEvents(muffinButton, Event.ONCLICK);
DOM.setEventListener(muffinButton, new EventListener() {
#Override
public void onBrowserEvent(Event event) {
Window.alert("You clicked on the anchor!");
// This is where your click handling for the link goes.
}
});
}
});
nextAnchorId++;
return infoWindow
}
A very simple solution is to use gwtquery:
Identify the anchor in the map you want to add the click handler and define a css selector for that (for instance id=my_link)
Use gquery to locate it and to add the event.
$('#my_link').click(new Function() {
public boolean f(Event e) {
[...]
return false; //false means stop propagation and prevent default
}
});
Note that gwtquery is not a wrapper of jquery but an entire gwt implementation of its api, so including it in your project will not overload it, and the compiler will pick up just the stuff you use.

GWT: In a TabLayoutPanel, how do I make tabs wrap if there are too many?

I'm using GWT 2.4. I have a TabLayoutPanel to which I add tabs. Each tab contains a ScrollPanel. My question is, how do I make the tabs in the tab bar wrap to the next line if the width of the tab bar exceeds the visible width?
Thanks, - Dave
GWT's TabLayoutPanel intentionally never wraps tabs. See lines 246-248 in TabLayoutPanel.java - (line 217 defines private static final int BIG_ENOUGH_TO_NOT_WRAP = 16384). You might be able to override this, but as #milan says, it's probably not good design.
Having multiple lines is, indeed, not recommended...
However, to be able to navigate left/right on a single tab bar with many tabs, you can use this recipe:
http://devnotesblog.wordpress.com/2010/06/17/scrollable-gwt-tablayoutpanel/
And an updated implementation that doesn't use the deprecated DeferredCommand:
package whatever.you.want;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* A {#link TabLayoutPanel} that shows scroll buttons if necessary
*/
public class ScrolledTabLayoutPanel extends TabLayoutPanel {
private static final int IMAGE_PADDING_PIXELS = 4;
private LayoutPanel panel;
private FlowPanel tabBar;
private Image scrollLeftButton;
private Image scrollRightButton;
private HandlerRegistration windowResizeHandler;
private ImageResource leftArrowImage;
private ImageResource rightArrowImage;
public ScrolledTabLayoutPanel(double barHeight, Unit barUnit,
ImageResource leftArrowImage, ImageResource rightArrowImage) {
super(barHeight, barUnit);
this.leftArrowImage = leftArrowImage;
this.rightArrowImage = rightArrowImage;
// The main widget wrapped by this composite, which is a LayoutPanel with the tab bar & the tab content
panel = (LayoutPanel) getWidget();
// Find the tab bar, which is the first flow panel in the LayoutPanel
for (int i = 0; i < panel.getWidgetCount(); ++i) {
Widget widget = panel.getWidget(i);
if (widget instanceof FlowPanel) {
tabBar = (FlowPanel) widget;
break; // tab bar found
}
}
initScrollButtons();
}
#Override
public void add(Widget child, Widget tab) {
super.add(child, tab);
checkIfScrollButtonsNecessary();
}
#Override
public boolean remove(Widget w) {
boolean b = super.remove(w);
checkIfScrollButtonsNecessary();
return b;
}
#Override
protected void onLoad() {
super.onLoad();
if (windowResizeHandler == null) {
windowResizeHandler = Window.addResizeHandler(new ResizeHandler() {
#Override
public void onResize(ResizeEvent event) {
checkIfScrollButtonsNecessary();
}
});
}
}
#Override
protected void onUnload() {
super.onUnload();
if (windowResizeHandler != null) {
windowResizeHandler.removeHandler();
windowResizeHandler = null;
}
}
private ClickHandler createScrollClickHandler(final int diff) {
return new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Widget lastTab = getLastTab();
if (lastTab == null)
return;
int newLeft = parsePosition(tabBar.getElement().getStyle().getLeft()) + diff;
int rightOfLastTab = getRightOfWidget(lastTab);
// Prevent scrolling the last tab too far away form the right border,
// or the first tab further than the left border position
if (newLeft <= 0 && (getTabBarWidth() - newLeft < (rightOfLastTab + 20))) {
scrollTo(newLeft);
}
}
};
}
/** Create and attach the scroll button images with a click handler */
private void initScrollButtons() {
scrollLeftButton = new Image(leftArrowImage);
int leftImageWidth = scrollLeftButton.getWidth();
panel.insert(scrollLeftButton, 0);
panel.setWidgetLeftWidth(scrollLeftButton, 0, Unit.PX, leftImageWidth, Unit.PX);
panel.setWidgetTopHeight(scrollLeftButton, 0, Unit.PX, scrollLeftButton.getWidth(), Unit.PX);
scrollLeftButton.addClickHandler(createScrollClickHandler(+20));
scrollLeftButton.setVisible(false);
scrollRightButton = new Image(rightArrowImage);
panel.insert(scrollRightButton, 0);
panel.setWidgetLeftWidth(scrollRightButton, leftImageWidth + IMAGE_PADDING_PIXELS, Unit.PX, scrollRightButton.getWidth(), Unit.PX);
panel.setWidgetTopHeight(scrollRightButton, 0, Unit.PX, scrollRightButton.getHeight(), Unit.PX);
scrollRightButton.addClickHandler(createScrollClickHandler(-20));
scrollRightButton.setVisible(false);
}
private void checkIfScrollButtonsNecessary() {
// Defer size calculations until sizes are available, when calculating immediately after
// add(), all size methods return zero
Scheduler.get().scheduleDeferred( new Scheduler.ScheduledCommand() {
#Override
public void execute() {
boolean isScrolling = isScrollingNecessary();
// When the scroll buttons are being hidden, reset the scroll position to zero to
// make sure no tabs are still out of sight
if (scrollRightButton.isVisible() && !isScrolling) {
resetScrollPosition();
}
scrollRightButton.setVisible(isScrolling);
scrollLeftButton.setVisible(isScrolling);
}
}
);
}
private void resetScrollPosition() {
scrollTo(0);
}
private void scrollTo(int pos) {
tabBar.getElement().getStyle().setLeft(pos, Unit.PX);
}
private boolean isScrollingNecessary() {
Widget lastTab = getLastTab();
if (lastTab == null)
return false;
return getRightOfWidget(lastTab) > getTabBarWidth();
}
private int getRightOfWidget(Widget widget) {
return widget.getElement().getOffsetLeft() + widget.getElement().getOffsetWidth();
}
private int getTabBarWidth() {
return tabBar.getElement().getParentElement().getClientWidth();
}
private Widget getLastTab() {
if (tabBar.getWidgetCount() == 0)
return null;
return tabBar.getWidget(tabBar.getWidgetCount() - 1);
}
private static int parsePosition(String positionString) {
int position;
try {
for (int i = 0; i < positionString.length(); i++) {
char c = positionString.charAt(i);
if (c != '-' && !(c >= '0' && c <= '9')) {
positionString = positionString.substring(0, i);
}
}
position = Integer.parseInt(positionString);
} catch (NumberFormatException ex) {
position = 0;
}
return position;
}
}

eclipse rcp :how to select a single cell in tableviewer?

hwo can I change the default selection behaviour of tables, I want to make a cell selected when user click it and make it editable when user double click it.
with #nonty 's help, I get what I want.
here is my cell highlighter implemention:
package com.amarsoft.rcputil;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.FocusCellOwnerDrawHighlighter;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
public class DefaultCellFocusHighlighter extends FocusCellOwnerDrawHighlighter {
public DefaultCellFocusHighlighter(ColumnViewer viewer) {
super(viewer);
}
protected boolean onlyTextHighlighting(ViewerCell cell) {
return false;
}
protected Color getSelectedCellBackgroundColor(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_DARK_BLUE);
}
protected Color getSelectedCellForegroundColor(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_WHITE);
}
protected Color getSelectedCellForegroundColorNoFocus(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_WHITE);
}
protected Color getSelectedCellBackgroundColorNoFocus(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_DARK_BLUE);
}
protected void focusCellChanged(ViewerCell newCell, ViewerCell oldCell) {
super.focusCellChanged(newCell, oldCell);
}
}
the code to use it :
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(tv,new DefaultCellFocusHighlighter(tv));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(tv) {
protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
TableViewerEditor.create(tv, focusCellManager, actSupport, ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION);
but I got new problem :
when I double click on cell to edit it's value, there is a little area at the left side of the cell is still highlighted with dark blue color
I know why :
When a text control is created with a border, the operating system includes a platform specific inset around the contents of the control.
still seeking for fixing...
Have a look at these two JFace Snippets:
Snippet036FocusBorderCellHighlighter - Demonstrates keyboard navigation by highlighting the currently selected cell with a focus border showing once more the flexibility of the new cell navigation support
Snippet034CellEditorPerRowNewAPI - Demonstrates different CellEditor-Types in one COLUMN with 3.3-API of JFace-Viewers
After digging through the code, I found the following method in the ColumnViewer class:
/**
* Hook up the editing support. Subclasses may override.
*
* #param control
* the control you want to hook on
*/
protected void hookEditingSupport(Control control) {
// Needed for backwards comp with AbstractTreeViewer and TableTreeViewer
// who are not hooked this way others may already overwrite and provide
// their
// own impl
if (viewerEditor != null) {
control.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
// Workaround for bug 185817
if (e.count != 2) {
handleMouseDown(e);
}
}
public void mouseDoubleClick(MouseEvent e) {
handleMouseDown(e);
}
});
}
}
So, I overrode that function within my TableViewer subclass:
#Override protected void hookEditingSupport(Control control) {
// We know there should be an editor avaiable
// if (viewerEditor != null) {
control.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
// Workaround for bug 185817
if (e.count != 2) {
// We don't want to edit on single clicks
// handleMouseDown(e);
}
}
public void mouseDoubleClick(MouseEvent e) {
// This method is private, so copy the implementation
// handleMouseDown(e);
ViewerCell cell = getCell(new Point(e.x, e.y));
e.count--; // A hack to make things work - pretend like it's a single click
if (cell != null) {
triggerEditorActivationEvent(new ColumnViewerEditorActivationEvent(
cell, e));
}
}
});
// }
}
This works for me. Tell me if it works for you.

How to disable copy/paste from/to EditText

In my application, there is a registration screen, where i do not want the user to be able to copy/paste text into the EditText field. I have set an onLongClickListener on each EditText so that the context menu showing copy/paste/inputmethod and other options does not show up. So the user won't be able to copy/ paste into the Edit fields.
OnLongClickListener mOnLongClickListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// prevent context menu from being popped up, so that user
// cannot copy/paste from/into any EditText fields.
return true;
}
};
But the problem arises if the user has enabled a third-party keyboard other than the Android default, which may have a button to copy/paste or which may show the same context menu. So how do i disable copy/paste in that scenario ?
Please let me know if there are other ways to copy/paste as well. (and possibly how to disable them)
Any help would be appreciated.
Best method is to use:
etUsername.setLongClickable(false);
If you are using API level 11 or above then you can stop copy,paste,cut and custom context menus from appearing by.
edittext.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
Returning false from onCreateActionMode(ActionMode, Menu) will prevent the action mode from being started(Select All, Cut, Copy and Paste actions).
You can do this by disabling the long press of the EditText
To implement it, just add the following line in the xml -
android:longClickable="false"
I am able to disable copy-and-paste functionality with the following:
textField.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
return false;
}
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode actionMode, MenuItem item) {
return false;
}
public void onDestroyActionMode(ActionMode actionMode) {
}
});
textField.setLongClickable(false);
textField.setTextIsSelectable(false);
Hope it works for you ;-)
Kotlin solution:
fun TextView.disableCopyPaste() {
isLongClickable = false
setTextIsSelectable(false)
customSelectionActionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu): Boolean {
return false
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem): Boolean {
return false
}
override fun onDestroyActionMode(mode: ActionMode?) {}
}
}
Then you can simply call this method on your TextView:
override fun onCreate() {
priceEditText.disableCopyPaste()
}
here is a best way to disable cut copy paste of editText work in all version
if (android.os.Build.VERSION.SDK_INT < 11) {
editText.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
menu.clear();
}
});
} else {
editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
return false;
}
});
}
In addition to the setCustomSelectionActionModeCallback, and disabled long-click solutions, it's necessary to prevent the PASTE/REPLACE menus from appearing when the text selection handle is clicked, as per the image below:
The solution lies in preventing PASTE/REPLACE menu from appearing in the show() method of the (non-documented) android.widget.Editor class. Before the menu appears, a check is done to if (!canPaste && !canSuggest) return;. The two methods that are used as the basis to set these variables are both in the EditText class:
isSuggestionsEnabled() is public, and may thus be overridden.
canPaste() is not, and thus must be hidden by introducing a function of the same name in the derived class.
A more complete answer is available here.
If you don't wan't to disable long click because you need to perform some functionality on long click than returning true is a better option to do so.
Your edittext long click will be like this.
edittext.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do Something or Don't
return true;
}
});
As per documentation
Returning "True" will indicate that long click have been handled so no need to perform default operations.
I tested this on API level 16, 22 and 25. Its working fine for me. Hope this will help.
Here is a hack to disable "paste" popup. You have to override EditText method:
#Override
public int getSelectionStart() {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getMethodName().equals("canPaste")) {
return -1;
}
}
return super.getSelectionStart();
}
Similar can be done for the other actions.
I've tested this solution and this works
mSubdomainEditText.setLongClickable(false);
mSubdomainEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
i added Extension Function in Kotlin language :
fun EditText.disableTextSelection() {
this.setCustomSelectionActionModeCallback(object : android.view.ActionMode.Callback {
override fun onActionItemClicked(mode: android.view.ActionMode?, item: MenuItem?): Boolean {
return false
}
override fun onCreateActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean {
return false
}
override fun onPrepareActionMode(mode: android.view.ActionMode?, menu: Menu?): Boolean {
return false
}
override fun onDestroyActionMode(mode: android.view.ActionMode?) {
}
})
}
you can use it like this :
edit_text.disableTextSelection()
also added below line in your xml :
android:longClickable="false"
android:textIsSelectable="false"
https://github.com/neopixl/PixlUI provides an EditText with a method
myEditText.disableCopyAndPaste().
And it's works on the old API
If you want to disable ActionMode for copy/pasting, you need to override 2 callbacks. This works for both TextView and EditText (or TextInputEditText)
import android.view.ActionMode
fun TextView.disableCopyPaste() {
isLongClickable = false
setTextIsSelectable(false)
customSelectionActionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu) = false
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu) = false
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem) = false
override fun onDestroyActionMode(mode: ActionMode?) {}
}
//disable action mode when edittext gain focus at first
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
customInsertionActionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu) = false
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu) = false
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem) = false
override fun onDestroyActionMode(mode: ActionMode?) {}
}
}
}
This extension is based off above #Alexandr solution and worked fine for me.
#Zain Ali, your answer works on API 11. I just wanted to suggest a way to do in on API 10 as well. Since I had to maintain my project API on that version, I was constantly playing with the functions available in 2.3.3 and got a possibility to do it. I have share the snippet below. I tested the code and it was working for me. I did this snippet on an urgency. Feel free to improve the code if there are any changes that can be done..
// A custom TouchListener is being implemented which will clear out the focus
// and gain the focus for the EditText, in few milliseconds so the selection
// will be cleared and hence the copy paste option wil not pop up.
// the respective EditText should be set with this listener
// tmpEditText.setOnTouchListener(new MyTouchListener(tmpEditText, tmpImm));
public class MyTouchListener implements View.OnTouchListener {
long click = 0;
EditText mEtView;
InputMethodManager imm;
public MyTouchListener(EditText etView, InputMethodManager im) {
mEtView = etView;
imm = im;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
long curr = System.currentTimeMillis();
if (click !=0 && ( curr - click) < 30) {
mEtView.setSelected(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mEtView.setSelected(true);
mEtView.requestFocusFromTouch();
imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
}
},25);
return true;
}
else {
if (click == 0)
click = curr;
else
click = 0;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mEtView.requestFocusFromTouch();
mEtView.requestFocusFromTouch();
imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
}
},25);
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
mEtView.setSelected(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mEtView.setSelected(true);
mEtView.requestFocusFromTouch();
mEtView.requestFocusFromTouch();
imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
}
},25);
return true;
}
return false;
}
For smartphone with clipboard, is possible prevent like this.
editText.setFilters(new InputFilter[]{new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.length() > 1) {
return "";
} return null;
}
}});
Read the Clipboard, check against the input and the time the input is "typed". If the Clipboard has the same text and it is too fast, delete the pasted input.
the solution is very simple
public class MainActivity extends AppCompatActivity {
EditText et_0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_0 = findViewById(R.id.et_0);
et_0.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//to keep the text selection capability available ( selection cursor)
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//to prevent the menu from appearing
menu.clear();
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
}
--------> preview <---------
Try Following custome class for prevant copy and paste in Edittext
public class SegoeUiEditText extends AppCompatEditText {
private final Context context;
#Override
public boolean isSuggestionsEnabled() {
return false;
}
public SegoeUiEditText(Context context) {
super(context);
this.context = context;
init();
}
public SegoeUiEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public SegoeUiEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
private void setFonts(Context context) {
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "Fonts/Helvetica-Normal.ttf"));
}
private void init() {
setTextIsSelectable(false);
this.setCustomSelectionActionModeCallback(new ActionModeCallbackInterceptor());
this.setLongClickable(false);
}
#Override
public int getSelectionStart() {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getMethodName().equals("canPaste")) {
return -1;
}
}
return super.getSelectionStart();
}
/**
* Prevents the action bar (top horizontal bar with cut, copy, paste, etc.) from appearing
* by intercepting the callback that would cause it to be created, and returning false.
*/
private class ActionModeCallbackInterceptor implements ActionMode.Callback, android.view.ActionMode.Callback {
private final String TAG = SegoeUiEditText.class.getSimpleName();
public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; }
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; }
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; }
public void onDestroyActionMode(ActionMode mode) {}
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
menu.clear();
return false;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(android.view.ActionMode mode) {
}
}
}
The solutions above do not take into account pasting with hardware keyboards (Ctrl+v). The easiest solution is to set a TextWatcher on your EditText, and filter characters you want or don't want in the afterTextChanged method. This works for all situations, i.e. typed characters, pastes, auto suggestions and auto corrections.
Rather than completely disabling all actions on the EditText, you may want to prevent only certain actions (like cut/copy, but not paste):
/**
* Prevent copy/cut of the (presumably sensitive) contents of this TextView.
*/
fun TextView.disableCopyCut() {
setCustomSelectionActionModeCallback(
object : Callback {
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?) = false
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
menu?.apply {
removeItem(android.R.id.copy)
removeItem(android.R.id.cut)
}
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?) = false
override fun onDestroyActionMode(mode: ActionMode?) {
// no-op
}
}
)
}
Actions that can be selectively removed:
removeItem(android.R.id.copy)
removeItem(android.R.id.cut)
removeItem(android.R.id.paste)
removeItem(android.R.id.shareText) // Share
removeItem(android.R.id.textAssist) // Open with Chrome
its very late but may it help someone .
add these lines in your edittext xml
android:longClickable="false"
android:textIsSelectable="false"
android:importantForAutofill="no"
I found that when you create an input filter to avoid entry of unwanted characters, pasting such characters into the edit text is having no effect. So this sort of solves my problem as well.
Solution that worked for me was to create custom Edittext and override following method:
public class MyEditText extends EditText {
private int mPreviousCursorPosition;
#Override
protected void onSelectionChanged(int selStart, int selEnd) {
CharSequence text = getText();
if (text != null) {
if (selStart != selEnd) {
setSelection(mPreviousCursorPosition, mPreviousCursorPosition);
return;
}
}
mPreviousCursorPosition = selStart;
super.onSelectionChanged(selStart, selEnd);
}
}
Try to use.
myEditext.setCursorVisible(false);
myEditext.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
return false;
}
});
Who is looking for a solution in Kotlin use the below class as a custom widget and use it in the xml.
class SecureEditText : TextInputEditText {
/** This is a replacement method for the base TextView class' method of the same name. This method
* is used in hidden class android.widget.Editor to determine whether the PASTE/REPLACE popup
* appears when triggered from the text insertion handle. Returning false forces this window
* to never appear.
* #return false
*/
override fun isSuggestionsEnabled(): Boolean {
return false
}
override fun getSelectionStart(): Int {
for (element in Thread.currentThread().stackTrace) {
if (element.methodName == "canPaste") {
return -1
}
}
return super.getSelectionStart()
}
public override fun onSelectionChanged(start: Int, end: Int) {
val text = text
if (text != null) {
if (start != text.length || end != text.length) {
setSelection(text.length, text.length)
return
}
}
super.onSelectionChanged(start, end)
}
companion object {
private val EDITTEXT_ATTRIBUTE_COPY_AND_PASTE = "isCopyPasteDisabled"
private val PACKAGE_NAME = "http://schemas.android.com/apk/res-auto"
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
disableCopyAndPaste(context, attrs)
}
/**
* Disable Copy and Paste functionality on EditText
*
* #param context Context object
* #param attrs AttributeSet Object
*/
private fun disableCopyAndPaste(context: Context, attrs: AttributeSet) {
val isDisableCopyAndPaste = attrs.getAttributeBooleanValue(
PACKAGE_NAME,
EDITTEXT_ATTRIBUTE_COPY_AND_PASTE, true
)
if (isDisableCopyAndPaste && !isInEditMode()) {
val inputMethodManager =
context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
this.setLongClickable(false)
this.setOnTouchListener(BlockContextMenuTouchListener(inputMethodManager))
}
}
/**
* Perform Focus Enabling Task to the widget with the help of handler object
* with some delay
* #param inputMethodManager is used to show the key board
*/
private fun performHandlerAction(inputMethodManager: InputMethodManager) {
val postDelayedIntervalTime: Long = 25
Handler().postDelayed(Runnable {
this#SecureEditText.setSelected(true)
this#SecureEditText.requestFocusFromTouch()
inputMethodManager.showSoftInput(
this#SecureEditText,
InputMethodManager.RESULT_SHOWN
)
}, postDelayedIntervalTime)
}
/**
* Class to Block Context Menu on double Tap
* A custom TouchListener is being implemented which will clear out the focus
* and gain the focus for the EditText, in few milliseconds so the selection
* will be cleared and hence the copy paste option wil not pop up.
* the respective EditText should be set with this listener
*
* #param inputMethodManager is used to show the key board
*/
private inner class BlockContextMenuTouchListener internal constructor(private val inputMethodManager: InputMethodManager) :
View.OnTouchListener {
private var lastTapTime: Long = 0
val TIME_INTERVAL_BETWEEN_DOUBLE_TAP = 30
override fun onTouch(v: View, event: MotionEvent): Boolean {
if (event.getAction() === MotionEvent.ACTION_DOWN) {
val currentTapTime = System.currentTimeMillis()
if (lastTapTime != 0L && currentTapTime - lastTapTime < TIME_INTERVAL_BETWEEN_DOUBLE_TAP) {
this#SecureEditText.setSelected(false)
performHandlerAction(inputMethodManager)
return true
} else {
if (lastTapTime == 0L) {
lastTapTime = currentTapTime
} else {
lastTapTime = 0
}
performHandlerAction(inputMethodManager)
return true
}
} else if (event.getAction() === MotionEvent.ACTION_MOVE) {
this#SecureEditText.setSelected(false)
performHandlerAction(inputMethodManager)
}
return false
}
}
}
A widely compatible solution (from Android 1.5 onwards) is
#Override
public boolean onTextContextMenuItem(int id) {
switch (id){
case android.R.id.cut:
onTextCut();
return false;
case android.R.id.paste:
onTextPaste();
return false;
case android.R.id.copy:
onTextCopy();
return false;
}
return true;
}
After spending a lot of time, removing the paste option in ContextMenu of EditText I have followed the below code in Java.
NoMenuEditText.Java
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import androidx.appcompat.widget.AppCompatEditText;
/**
* custom edit text
*/
public class NoMenuEditText extends AppCompatEditText {
private static final String EDITTEXT_ATTRIBUTE_COPY_AND_PASTE = "isCopyPasteDisabled";
private static final String PACKAGE_NAME = "http://schemas.android.com/apk/res-auto";
public NoMenuEditText(Context context) {
super(context);
}
public NoMenuEditText(Context context, AttributeSet attrs) {
super(context, attrs);
EnableDisableCopyAndPaste(context, attrs);
}
/**
* Enable/Disable Copy and Paste functionality on EditText
*
* #param context Context object
* #param attrs AttributeSet Object
*/
private void EnableDisableCopyAndPaste(Context context, AttributeSet attrs) {
boolean isDisableCopyAndPaste = attrs.getAttributeBooleanValue(PACKAGE_NAME,
EDITTEXT_ATTRIBUTE_COPY_AND_PASTE, false);
if (isDisableCopyAndPaste && !isInEditMode()) {
InputMethodManager inputMethodManager = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
this.setLongClickable(false);
this.setOnTouchListener(new BlockContextMenuTouchListener
(inputMethodManager));
}
}
/**
* Perform Focus Enabling Task to the widget with the help of handler object
* with some delay
*/
private void performHandlerAction(final InputMethodManager inputMethodManager) {
int postDelayedIntervalTime = 25;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
NoMenuEditText.this.setSelected(true);
NoMenuEditText.this.requestFocusFromTouch();
inputMethodManager.showSoftInput(NoMenuEditText.this,
InputMethodManager.RESULT_SHOWN);
}
}, postDelayedIntervalTime);
}
/**
* Class to Block Context Menu on double Tap
* A custom TouchListener is being implemented which will clear out the focus
* and gain the focus for the EditText, in few milliseconds so the selection
* will be cleared and hence the copy paste option wil not pop up.
* the respective EditText should be set with this listener
*/
private class BlockContextMenuTouchListener implements View.OnTouchListener {
private static final int TIME_INTERVAL_BETWEEN_DOUBLE_TAP = 30;
private InputMethodManager inputMethodManager;
private long lastTapTime = 0;
BlockContextMenuTouchListener(InputMethodManager inputMethodManager) {
this.inputMethodManager = inputMethodManager;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
long currentTapTime = System.currentTimeMillis();
if (lastTapTime != 0 && (currentTapTime - lastTapTime)
< TIME_INTERVAL_BETWEEN_DOUBLE_TAP) {
NoMenuEditText.this.setSelected(false);
performHandlerAction(inputMethodManager);
return true;
} else {
if (lastTapTime == 0) {
lastTapTime = currentTapTime;
} else {
lastTapTime = 0;
}
performHandlerAction(inputMethodManager);
return true;
}
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
NoMenuEditText.this.setSelected(false);
performHandlerAction(inputMethodManager);
}
return false;
}
}
#Override
protected void onSelectionChanged(int selStart, int selEnd) {
CharSequence text = getText();
if (text != null) {
if (selStart != text.length() || selEnd != text.length()) {
setSelection(text.length(), text.length());
return;
}
}
super.onSelectionChanged(selStart, selEnd);
}
#Override
public boolean isSuggestionsEnabled() {
return false;
}
#Override
public int getSelectionStart() {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getMethodName().equals("canPaste")) {
return -1;
}
}
return super.getSelectionStart();
}
}
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NoMenuEditText edt_username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_username = (NoMenuEditText) findViewById(R.id.edt_username);
edt_username.setLongClickable(false);
edt_username.setTextIsSelectable(false);
edt_username.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
}
}
drawable- zeropx.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="0dp"
android:height="0dp"/>
</shape>
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="NoMenuEditText">
<attr name="isCopyPasteDisabled" format="boolean" />
</declare-styleable>
</resources>
At Last, I finally Removed the paste option from the Context Menu of EditText
Thank you StackOverflow posts and http://androidinformative.com/disabling-context-menu/
editText.apply {
setOnTouchListener { v, event ->
if (event.action == KeyEvent.ACTION_DOWN) {
requestFocus()
setSelection(text.toString().length)
showKeyboard()
return#setOnTouchListener true
}
}
}
fun View.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, 0)
}
Actually in my case i had to set the callback for both selection and insertion and only then i got the copy/paste pop-up to not appear anymore.
Something like this :
private void disableCopyPaste() {
input.setLongClickable(false);
input.setTextIsSelectable(false);
final ActionMode.Callback disableCopyPasteCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
};
input.setCustomSelectionActionModeCallback(disableCopyPasteCallback);
input.setCustomInsertionActionModeCallback(disableCopyPasteCallback);
}
Similar to GnrlKnowledge, you can clear the Clipboard
http://developer.android.com/reference/android/text/ClipboardManager.html
If you want, preserve the text in the Clipboard, and on onDestroy, you can set it again.