In the below code snippet (only the listener portion), i want to use the Single Tap only for Tapping the capture and Swiping if you are swiping.
In onTouch() if I return false then it gives me the Single Tapping feature and if I return true then I can handle the swipe feature using both ACTION_DOWN and ACTION_UP.
In Case of Tapping If I am trying to handle using both the action it's not happening, only through ACTION_DOWN it's getting.
Please help me out for the same.
this.setOnTouchListener(new OnSwipeTouchListener(getContext()) {
public void onSwipeTop() {
Toast.makeText(getContext(), "top", Toast.LENGTH_SHORT).show();
}
public void onSwipeRight() {
Toast.makeText(getContext(), "right", Toast.LENGTH_SHORT).show();
}
public void onSwipeLeft() {
Toast.makeText(getContext(), "left", Toast.LENGTH_SHORT).show();
}
public void onSwipeBottom() {
Toast.makeText(getContext(), "bottom", Toast.LENGTH_SHORT).show();
}
public boolean onTouch(View v, MotionEvent event) {
switch(e.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = e.getX();
case MotionEvent.ACTION_UP:
x2 = e.getX();
break;
}
Toast.makeText(getContext(),"touch",Toast.LENGTH_SHORT).show();
return false;
}
});
Related
I don't know if this is common or what. But I only have one Toast when it successfully deleted the data from Realtime Database
here's my code btw.
holder.btndel_stud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Delete Student Record");
alert.setMessage("Are you sure you want to delete");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
final String uniqueKey = addingStudentsArrayList.get(position).getUniqueid();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child(uniqueKey).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(context, "Student Account/Record has been deleted..", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Something went wrong...", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
alert.show();
}
});
}
basically it toast twice on my mobile phone, even tho I called it only once. But yeah it toast once in my emulator. I genuinely don't know what's happening since there's no message indicating why it's toasting twice.
Toast.makeText(context, "Student Account/Record has been deleted..", Toast.LENGTH_SHORT).show();
The solutions I've tried:
Reinstall the app on my phone, clear cache and clear storage but no luck. Thank you!
So i have an app connected to firebase. The app retrieves data(a string) from firebase into a text view and then the TextToSpeech feature reads the text out(not from the textView but it itself retrieves the same data from firebase real-time database). I have used onDataChange() meathod so the texttospeech feature reads the text out as soon as any change in the data occurs on firebase, and not on the click of any button. Now i want to place a toggle button in my app and use it to either turn the tts feature on or off but i cant get it to work. When the toggle button is off, i want the texttospeech feature to stop and when the button state is on, i want the texttospeech feature to turn back on.This is what ive tried:
mtts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
mtts.setLanguage(Locale.US); }else{
Toast.makeText(MainActivity.this, "Couldnt initialize speech function!", Toast.LENGTH_SHORT).show();
}
}
}); mIvToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
reff = FirebaseDatabase.getInstance().getReference().child("Match").child("Screen1");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String tts= dataSnapshot.getValue().toString();
mtts.speak(tts, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}else{
mtts.stop();
mtts.shutdown();
}
}
});
TIA !
When you attach a valueEventListener the listener will trigger as long as there is change in the data, even though you checked the toggle to off. So the thing that you should do is to remove the listener when you are done:
Directly under this:
mtts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
mtts.setLanguage(Locale.US);
}else{
Toast.makeText(MainActivity.this, "Couldnt initialize speech function!", Toast.LENGTH_SHORT).show();
}
}
});
Add these:
//the reference
reff=FirebaseDatabase.getInstance().getReference().child("Match").child("Screen1");
//make a listener
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String tts= dataSnapshot.getValue().toString();
mtts.speak(tts, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
//toggle
mIvToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
//add listener
reff.addValueEventListener(listener);
}else{
//remove listener
reff.removeEventListener(listener);
mtts.stop();
mtts.shutdown();
}
}
});
I am working on floating Keyboard using Recycler view which would appear on screen when a button is clicked and dismisses when Right / Left swipe is done. As I am doing so I observed the swiping the keyboard is not smoother (Some times swipe listeners does not detect swipe gestures.) . Then I referred the following links and re-worked,
https://medium.com/#euryperez/android-pearls-detect-swipe-and-touch-over-a-view-203ae2c028dc
https://stackoverflow.com/questions/4139288/android-how-to-handle-right-to-left-swipe-gestures.
I added gesture listeners to the child of Recycler view and used three override methods onClick(), onSwipeRight() and onSwipeLeft(). The position of the onClick is obtained perfectly but sometimes Swipe Listeners are not detected this makes users to feel swiping is not smoother.
All I needed is to make swipe smoother and detecting position of clicking keys without compromising both. Is there any ways to implement these feature if there any way suggest me!. Here is my code. Thanks in Advance !.
public ViewHolder(View v) {
super(v);
textView = (TextView) v.findViewById(R.id.textView);
imageView = (ImageView) v.findViewById(R.id.imageView);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);
mBodyContainer = (ConstraintLayout) v.findViewById(R.id.body_container);
cllayout = (RelativeLayout) v.findViewById(R.id.cllayout);
setSwipeGestureForParent(cllayout);
}
private void setSwipeGestureForParent(final View view) {
view.setOnTouchListener(new OnSwipeTouchListener(mContext) {
#Override
public boolean onTouch(View v, MotionEvent event) {
parentview.stopScroll();
String view = item.text;
if (view.equals("")) {
} else if (v.getId() != R.id.body_container && !view.equals("")) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
imageView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_keyboard_key_selected));
break;
case MotionEvent.ACTION_MOVE:
imageView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_keyboard_key_selected));
break;
case MotionEvent.ACTION_BUTTON_PRESS:
imageView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_keyboard_key_selected));
break;
default:
imageView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.bg_keyboard_key_normal));
break;
}
}
return super.onTouch(v, event);
}
#Override
public void onClick() {
super.onClick();
Toast.makeText(mContext, "onclick", Toast.LENGTH_SHORT).show();
}
#Override
public void onSwipeLeft() {
Toast.makeText(mContext, "Swipeleft", Toast.LENGTH_SHORT).show();
}
#Override
public void onSwipeRight() {
Toast.makeText(mContext, "SwipeRight", Toast.LENGTH_SHORT).show();
}
});
}
I have prepared 2 general 'copy-and-paste' classes for you so you can very easily use all gestures on the RecyclerView.
1 - GestureDetector - just add it to your project
class OnSwipeTouchListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context ctx, TouchListener touchListener) {
gestureDetector = new GestureDetector(ctx, new GestureListener(touchListener));
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 300;
private static final int SWIPE_VELOCITY_THRESHOLD = 300;
private TouchListener touchListener;
GestureListener(TouchListener touchListener) {
super();
this.touchListener = touchListener;
}
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.i("TAG", "onSingleTapConfirmed:");
touchListener.onSingleTap();
return true;
}
#Override
public void onLongPress(MotionEvent e) {
Log.i("TAG", "onLongPress:");
touchListener.onLongPress();
}
#Override
public boolean onDoubleTap(MotionEvent e) {
touchListener.onDoubleTap();
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
touchListener.onSwipeRight();
} else {
touchListener.onSwipeLeft();
}
result = true;
}
} else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
touchListener.onSwipeDown();
} else {
touchListener.onSwipeUp();
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
}
2 - TouchListener - just add the interface definition to your project. To make the use even more easy, I have used some default implementations of the interface. So, you need to add to your module's build.gradle:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
Add the interface:
public interface TouchListener {
void onSingleTap();
default void onDoubleTap() {
Log.i("TAG", "Double tap");
}
default void onLongPress() {
Log.i("TAG", "Long press");
}
default void onSwipeLeft() {
Log.i("TAG", "Swipe left");
}
default void onSwipeRight() {
Log.i("TAG", "Swipe right");
}
default void onSwipeUp() {
Log.i("TAG", "Swipe up");
}
default void onSwipeDown() {
Log.i("TAG", "Swipe down");
}
}
3 - Now you can attach to any view the TouchListener and implement only those methods you really need. An example is:
holder.anyview.setOnTouchListener(new OnSwipeTouchListener(mCtx, new TouchListener() {
#Override
public void onSingleTap() {
Log.i("TAG", ">> Single tap");
}
#Override
public void onDoubleTap() {
Log.i("TAG", ">> Double tap");
}
#Override
public void onLongPress() {
Log.i("TAG", ">> "Long press");
}
#Override
public void onSwipeLeft() {
Log.i("TAG", ">> Swipe left");
}
#Override
public void onSwipeRight() {
Log.i("TAG", ">> Swipe right");
}
}));
That's all! Enjoy.
I implemented a navigation drawer and had used fragments. Now i can switch to fragments from the drawer menu. But when i press back, my app closes from that fragment and don't know how to go back to the main activity.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
displaySelectedScreen(id);
return true;
}
private void displaySelectedScreen(int id) {
Fragment frag = null;
switch (id) {
case R.id.trigger:
break;
case R.id.setup:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
frag = new SettingsF();
break;
case R.id.recordings:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#4E342E"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8D6E63")));
break;
case R.id.howto:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
case R.id.about:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
case R.id.email_us:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main, frag);
ft.addToBackStack(ft.getClass().getSimpleName()).commit();
}
DrawerLayout drawer = findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
And here is the setting fragment only:
public class SettingsF extends ListFragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_settings, container, false);
String[] datasource = {"Trusted Contacts", "Custom Text Set-Up"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.txtitems, datasource);
setListAdapter(adapter);
setRetainInstance(true);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Context Set-Up");
}
public void onListItemClick(ListView l, View view, int position, long id) {
ViewGroup viewGroup = (ViewGroup) view;
TextView tv = (TextView) viewGroup.findViewById(R.id.txtitems);
Toast.makeText(getActivity(), tv.getText().toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener( new View.OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
//Already Used Intent, doesn't work
return true;
}
return false;
}
} );
super.onResume();
}
}
I updated the question. I already used addToBackStack(), then overrided the method onResume() but still the app terminates when pressing the back button.
I'm really that new to this, so don't misunderstand me what did i implemented throughout the codes.
Thanks In Advance
for Hardware backbutton
add this code in onResume method in fragment
//You need to add the following line
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
//here use intent to call mainActivity
return true;
}
return false;
}
} );
hope this will help you
Add this line after ft.replace():
ft.addToBackStack(null);
This line will make it so that each time you select an item from the navigation drawer, a history of fragments is built up. Then when you press the back button, you'll go back through the history. If you have no history items, the app will close.
A more sophisticated implementation might use a name argument (like "FragA" or "FragB") instead of null as the argument for addToBackStack(), and then check to see if your fragment already exists in the back stack instead of always opening a new one. That way if you went A->B->A->B->A->B you wouldn't have three copies of A and two copies of B in the history.
private void gotoRightClick() {
textArea.setOnMouseClicked(new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent event) {
if(event.isSecondaryButtonDown())
{
System.out.println("right click pressed in text area");
}
}
});
tableView.setOnMouseClicked(new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent e) {
if(e.isSecondaryButtonDown())
{
System.out.println("right click pressed in table view");
}
}
});
}
None of the event is detecting can any one help me?
Thanks Advance
Try this:
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.SECONDARY)) {
//do something
}
}
});