How to Handle the OnItemClick and OnItemLongClick event while the ListView has setOnTouchListener - android-listview

A ListView that I have setting the onTouchListener to implementate the item swipe function, and I still need the onItemClick and the onItemLongClick event, but I can't do it.
while I do noting int the onTouch function, and return false, the onItemClick or the longClick will response.the code like this:
public boolean onTouch(View v, MotionEvent event) {
return false
}
But when I have done something and then at the Action_Up I return it false, the click event no response.somting like that:
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Todo something
break;
case MotionEvent.ACTION_MOVE:
// Todo something
break;
case MotionEvent.ACTION_UP:
// Todo something
if (the Condition) {
return true;
} else {
return false;
}
break;
default:
break;
}
return true;
}
I don't know why. I have search this for few days, and until now I still don't know how to do it.Please help me.

I have found the way. By the way, there are many libs to do this.

Related

Public List In MainActivity and MVVM

I need some help with MVVM architecture.
I have a RecyclerView that receives LiveData and display it perfectly, however, my recyclerView requires another source of Data to customize colors and backgrounds of TextViews. for now I'm using a public list declared in the Mainactivity, But I've read that it's not a good practice.
is it possible to perform a non-live request to database from inside RecyclerView, in order to replace the public list ? if not I would really like some suggestions.
here is my onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull ResultRecyclerViewAdapter.ResultHolder holder, int position) {
Results currentResult = results.get(position);
holder.ston1.setText(currentResult.getSton1());
holder.ston2.setText(String.valueOf(currentResult.getSton2()));
holder.ston1.setBackgroundColor(0xFF12FF45);
holder.ston2.setBackgroundColor(0xFF12FF45);
holder.ston1.getBackground().setAlpha(100);
holder.ston2.getBackground().setAlpha(100);
for (Ston ston: MainActivity.Stons){
if (currentResult.getStonCode().equals(ston.getStonCode()) && currentResult.getStonType().equals(ston.getStonType())){
switch (ston.getStonSelected()) {
case "WADS":
holder.ston1.getBackground().setAlpha(255);
break;
case "WQAS":
holder.ston2.getBackground().setAlpha(255);
break;
}
break;
}
}
holder.ston1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean found = false;
for (Ston ston: MainActivity.Stons){
if (currentResult.getStonCode().equals(ston.getStonCode())){
found = true;
break;
}
}
if (!found) {
holder.ston1.getBackground().setAlpha(255);
MainActivity.Stons.add(new Stons(currentResult.getStonCode(),"WADS",
currentResult.getStonType()));
}
else {
for (Ston ston : MainActivity.Stons) {
if (currentResult.getStonCode().equals(ston.getStonCode()) && ston.getStonSelected().equals("WADS") &&
ston.getStonType().equals(currentResult.getStonType())){
MainActivity.Stons.remove(ston);
holder.ston1.getBackground().setAlpha(100);
break;
}
}
}
}
});
holder.ston2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Boolean found = false;
for (Ston ston: MainActivity.Stons){
if (currentResult.getStonCode().equals(ston.getStonCode())){
found = true;
break;
}
}
if (!found) {
holder.ston2.getBackground().setAlpha(255);
MainActivity.Stons.add(new Stons(currentResult.getStonCode(),"WQAS",
currentResult.getStonType()));
}
else {
for (Ston ston : MainActivity.Stons) {
if (currentResult.getStonCode().equals(ston.getStonCode()) && ston.getStonSelected().equals("WQAS") &&
ston.getStonType().equals(currentResult.getStonType())){
MainActivity.Stons.remove(ston);
holder.ston2.getBackground().setAlpha(100);
break;
}
}
}
}
});
One option that I see is to create new type specifically for your recyclerview adapter that will hold both Results object and information that you use for background alpha. So in your activity (or fragment) when livedata observer is triggered you don't directly pass it to adapter, but first create collection of objects of your new type, and then pass it to adapter. And I strongly suggest you to use Kotlin if possible, there you can use collection mapping to map collection from the db to your new type's collection.

GWT: How to disable the anchor link event when clicked

I want to disable the anchor link event when it clicked one time. I used anchor.setenabled(false) but nothing happend. When I click the same button again the event e is true. I want false at that time.
public void onCellClick(GridPanel grid, int rowIndex, int colindex,EventObject e)
{
if(rowIndex==0 && colindex==2){
tomcatHandler = "Start";
anchorStart.setEnabled(false);
}else if(rowIndex==0 && colindex==3){
tomcatHandler = "Stop";
****anchorStop.setEnabled(false);
anchorStart.setEnabled(false);
anchorRestart.setEnabled(true);****
}else if(rowIndex==0 &&colindex==4){
tomcatHandler = "Restart";
anchorRestart.setEnabled(false);
}
AdminService.Util.getInstance().tomcat(tomcatHandler,new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
imageChangeEvent(result);
}
#Override
public void onFailure(Throwable caught) {
}
});}
Anchors in GWT have always had a problem with setEnabled() because HTML doesn't support such a property. A quick workaround is to create a new widget that subclasses GWT's Anchor, adding the following override:
#Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONDBLCLICK:
case Event.ONFOCUS:
case Event.ONCLICK:
if (!isEnabled()) {
return;
}
break;
}
super.onBrowserEvent(event);
}
This disables the passing of the browser event to GWT's Anchor class (summarily disabling all related handlers) when the link is double clicked, focused or clicked and is in a disabled state.
Source
It doesn't seem to actually disable the anchor, but it does retain the status that has been set with anchor.setEnabled(), so just test that within your handler e.g.
myAnchor.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent evt) {
// write to filter and then call reload
if (((Anchor) evt.getSource()).isEnabled()) {
//do stuff
}
}
});

Allow only numbers in textbox in GWT?

I have a requirement where i need to allow only numbers in text box. if user tries to enter any other character other than numbers then we need to cancel the event. Please help me how to achieve this?
Thanks!
You just have to validate the users input on a certain event. It can be e.g. on every keystroke (KeyPressEvent), when the TextBox loses focus (ValueChangeEvent), on a button press (ClickEvent), and so on. You implement an event handler, e.g. KeyPressHandler and register your implementation with the TextBox. Then in your handler you validate the TextBox value and if it contains something else than numbers, you just return from the method, probably somehow telling the user that the value was invalid.
Something like this:
final TextBox textBox = new TextBox();
textBox.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
String input = textBox.getText();
if (!input.matches("[0-9]*")) {
// show some error
return;
}
// do your thang
}
});
If you have a lot of validation to do, you probably want to introduce some validation framework which saves you from a lot of reinventing the wheel. There may be better alternatives nowadays but personally I have been quite satisfied with the GWT-VL validation framwork.
The following is a more generic approach and allows for code reuse. You can use the NumbersOnly handler for any textbox (of the same class) you wish.
intbox1.addKeyPressHandler(new NumbersOnly());
intbox2.addFocusHandler(new OnFocus());
//inner class
class NumbersOnly implements KeyPressHandler {
#Override
public void onKeyPress(KeyPressEvent event) {
if(!Character.isDigit(event.getCharCode()))
((IntegerBox)event.getSource()).cancelKey();
}
}
class NumbersOnly implements KeyPressHandler {
#Override
public void onKeyPress(KeyPressEvent event) {
if (!Character.isDigit(event.getCharCode())
&& event.getNativeEvent().getKeyCode() != KeyCodes.KEY_TAB
&& event.getNativeEvent().getKeyCode() != KeyCodes.KEY_BACKSPACE){
((IntegerBox) event.getSource()).cancelKey();
}
}
}
I added other exceptions for example the possibility to copy the number. It still prevents the pasting of things from clipboard.
public class NumbersOnlyKeyPressHandler implements KeyPressHandler {
#Override
public void onKeyPress(KeyPressEvent event) {
switch(event.getNativeEvent().getKeyCode()) {
case KeyCodes.KEY_TAB:
case KeyCodes.KEY_BACKSPACE:
case KeyCodes.KEY_DELETE:
case KeyCodes.KEY_LEFT:
case KeyCodes.KEY_RIGHT:
case KeyCodes.KEY_UP:
case KeyCodes.KEY_DOWN:
case KeyCodes.KEY_END:
case KeyCodes.KEY_ENTER:
case KeyCodes.KEY_ESCAPE:
case KeyCodes.KEY_PAGEDOWN:
case KeyCodes.KEY_PAGEUP:
case KeyCodes.KEY_HOME:
case KeyCodes.KEY_SHIFT:
case KeyCodes.KEY_ALT:
case KeyCodes.KEY_CTRL:break;
default:
if(event.isAltKeyDown() || (event.isControlKeyDown() && (event.getCharCode() != 'v'&& event.getCharCode() != 'V')) )
break;
if(!Character.isDigit(event.getCharCode()))
if(event.getSource() instanceof IntegerBox)
((IntegerBox)event.getSource()).cancelKey();
}
}
}
Replace your TextBox with either an IntegerBox or LongBox.
This is not semantically the same as only allowing digits, but it's arguably better in most use cases.
You will also get the in and out integer parsing done for free.
Try this one:
public void onKeyPress(KeyPressEvent event) {
if(event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_DELETE &&
event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_BACKSPACE &&
event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_LEFT &&
event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_RIGHT){
String c = event.getCharCode()+"";
if(RegExp.compile("[^0-9]").test(c))
textbox.cancelKey();
}
}
you can validate it through javascript method:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
your text box will be like this
<input class="txtStyle" type="text" autocomplete="off" onkeypress ="return isNumberKey(event);" />
The ValueBox is not primary designed to filter input.
Why? Because the user will count your app enter into ANR or corrupted when he presses keys of desktop keyboard, yes?
That s not a phone with its separated types of keyset, yes?
So the only solution here is to signal people they put in wrong characters by , e.g., red coloring.
Let me submit an example code:
IntegerBox field = new IntegerBox();
field.setStyleName("number_ok");
field.addKeyUpHandler(event -> {
String string = field.getText();
char[] harfho = string.toCharArray();
for (char h : harfho) {
try {
Integer.parseInt(""+h);
} catch (NumberFormatException e) {
field.setStyleName("number_error");
return;
}
}
field.setStyleName("number_ok");
});
and in css:
.number_error{
background-color: red;
}
.number_ok{
background-color: transparent;
}
I had the same issue (using an IntegerBox which is more or less the same thing) and did it like this;
fieldName.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
// Prevent anyone entering anything other than digits here
if (!Character.isDigit(event.getCharCode())) {
((IntegerBox) event.getSource()).cancelKey();
return;
}
// Digits are allowed through
}
});

GWT pasting event

I want to handle events when user pastes some text in TextBox. Which event is fired in this situation? I tried ValueChange and Change handlers, but they didn't work.
This might help you. Describes a workaround to hook to the onpaste event.
In short:
subclass TextBox
sink the onpaste event in the constructor
sinkEvents(Event.ONPASTE);
override onBrowserEvent(Event event)
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (event.getTypeInt()) {
case Event.ONPASTE: {
// do something here
break;
}
}
}
GWT does not yet have support for cut, copy & paste: http://code.google.com/p/google-web-toolkit/issues/detail?id=4030
Edited:
Another option is to use JSNI. For example add this to your GWT class:
public native void addCutHandler(Element element)
/*-{
var temp = this; // hack to hold on to 'this' reference
element.oncut = function(e) {
temp.#org.package.YourClass::handleCut()();
}
}-*/;
public void handleCut() {
Window.alert("Cut!");
}
**(Write In the Constructor)**
sinkEvents( Event.ONPASTE );
**(After that write below code)**
public void onBrowserEvent( Event event )
{
super.onBrowserEvent( event );
switch ( event.getTypeInt() )
{
case Event.ONPASTE :
{
event.stopPropagation();
event.preventDefault();
break;
}
}
}

GWT Tree widgets swallow arrow keyboard events which make TextBoxes contained in TreeItems not respond to arrow keys

Easily reproducible in GWT 1.6.4:
Tree tree = new Tree();
tree.addItem(new TextBox());
The problem lies with onBrowserEvent in Tree:
switch (eventType) {
case Event.ONKEYDOWN:
case Event.ONKEYUP: {
if (isArrowKey(DOM.eventGetKeyCode(event))) {
DOM.eventCancelBubble(event, true);
DOM.eventPreventDefault(event);
return;
}
}
Like a lot of GWT widgets, they don't subclass well. There has to be a simple trick I could swing for this?
Solved this with a bit of a hack.
m_tree = new Tree()
{
#Override
protected boolean isKeyboardNavigationEnabled(TreeItem inCurrentItem)
{
return false;
}
#Override
public void onBrowserEvent(Event event) {
int eventType = DOM.eventGetType(event);
switch (eventType)
{
case Event.ONKEYDOWN:
case Event.ONKEYPRESS:
case Event.ONKEYUP:
return;
default:
break;
}
super.onBrowserEvent(event);
}
};