how to implement same action for textview and button? - java

I want to have same thing happen when I press a button as I press enter on text edit(s).
Here is implementation of OnEditorActionListener for text edit:
private OnEditorActionListener clickedEnter = (new OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//implemtation of task1
}
return false;
}
});
And here is implementation for the button:
show.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//How can I call clickedEnter here?
}
});
The reason is, I want to have less code and easier debugging etc. Thanks in advance.

Edit:
final EditText editText = (EditText) findViewById(R.id.textView);
editText.setOnEditorActionListener(clickedEnter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.onEditorAction(EditorInfo.IME_ACTION_DONE);
}
});
And here's my xml:
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="200dp "
android:text="Done!"/>
<EditText
android:id="#+id/textView"
android:inputType="text"
android:singleLine="true"
android:imeOptions="actionDone"
android:textSize="30dp"
android:textColor="#333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="Enter text"/>
Depends on what action you want to invoke within the editor.

You can either create a method and call it in the two functions, or call show.performClick() in the first method.
Solution 1:
private OnEditorActionListener clickedEnter = (new OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
yourMethod();
}
return false;
}
});
show.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
yourMethod();
}
});
private void yourMethod(){
//Instructions
}
Solution 2 :
private Button show;
private OnEditorActionListener clickedEnter = (new OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
show.performClick();
}
return false;
}
});
show.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Instructions...
}
});

you can make a different method for your task and call that method in both the listener's events.

I think you want something like this
etOne.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
bSearch.performClick();
closeKeyboard(getActivity(),
etOne.getWindowToken());
return true;
}
return false;
}
});
and
bSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Do something..
}
});
now the button will //Do something .. and if you want that when user press enter on keyboard and the same thing happens as what the button does.. just call bSearch.performClick(); hope it helps..
Edit : also closeKeyboard(getActivity(),etOne.getWindowToken()); will auto hide the soft keyboard after hitting enter.

Related

Handling onClick and double click

I have a messaging app similar to whatsapp where there are messages videos and images in the chat activity. Now I want to implement a double tap like feature on this but the problem is I also have a onclicklistner attached to my image and video frame that opens up a fullscreenactivity showing the image in fullscreen or playing the video in fullscreen. So on double tap instead of liking the picture or video it simply opens the video or image in the fullscreen mode. Since in messages I don't have a onclick listner attached double tap like works fine. Any ideas on how I can make the double tap like work in case of the videos or images. I am fairly new to android development using Java. So any help is appreciated.
HI, I think the approach to take depends on the future of your app, using LongClick is kinda good but what if you want to achieve a zoom like onLongClick?
What I did below is that I created a subclass that extends GestureDetector.SimpleOnGestureListener and then in my GestureTest class, I an ontouchListener and return the gesture instance created before, finally I parse the listener to the button that has to perform the clicks, it can be any View object.
Finally, I used the TextView I created to display/monitor my actions.
GestureDetector like below:
public class GestureTest extends AppCompatActivity{
private Button btn;
private TextView actions;
private GestureDetector mDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gesture_test);
btn = findViewById(R.id.btn);
actions = findViewById(R.id.action);
mDetector = new GestureDetector(this, new SampleGestureListener());
View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return mDetector.onTouchEvent(event);
}
};
btn.setOnTouchListener(touchListener);
}
public class SampleGestureListener extends GestureDetector.SimpleOnGestureListener{
#Override
public boolean onDown(MotionEvent event) {
Log.e("EVENT","BUTTON PRESSED DOWN, NOT YET RELEASED WILL TRIGGER ONLONG-PRESS");
// don't return false here or else none of the other
// gestures will work
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.e("EVENT", "SINGLE CLICK EVENT");
actions.setText("THIS CLICK IS FOR IMAGE OR VIDEO TO OPEN ?");
return true;
}
#Override
public void onLongPress(MotionEvent e) {
Log.e("EVENT", "LONG PRESSED");
actions.setText("THIS IS ZOOM LIKE NOT DOUBLE CLICK!!!");
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.e("EVENT", "DOUBLE CLICKED HAPPENED");
actions.setText("THIS CLICK IS TO LIKE IMAGE OR VIDEO ?");
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
Log.e("EVENT", "SCROLLING");
actions.setText("YOU\" Scrolling on many images...");
return true;
}
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.e("EVENT", "FLINGED");
actions.setText("THIS IS TINDER FLING LIKE ?");
return true;
}
}
}
AND BELOW IS MY activity_gesture_test.xml FOR TESTING:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btn"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="100dp"/>
<TextView
android:id="#+id/action"
android:textSize="20dp"
android:textColor="#color/black"
app:layout_constraintTop_toBottomOf="#+id/btn"
android:layout_width="match_parent"
android:layout_height="100dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
GoodLuck Coding.
try this for double click:
int i = 0;
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
i++;
Handler handler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
i = 0;
}
};
if (i == 1) {
//Single click
handler.postDelayed(r, 250);
} else if (i == 2) {
//Double click
i = 0;
ShowDailog();
}
}
});
and for click listener:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
It is generally accepted to use long tap instead of double click in android apps. Try this:
yourView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
//do Your stuff here
return true;
}
});

onKeyListener not firing an event in Android

I have an Activity with one Fragment. This fragment has one button, and I want something to happen when I push the "enter" button on my hardware keyboard (I am testing it with adb keyevent).
I've read a lot of solutions here on stackoverflow, but none of them worked.
This is my fragment code:
btnPhoto = (Button) rootView.findViewById(R.id.taskBtnPhoto);
photoView = (ImageView) rootView.findViewById(R.id.taskPhotoView);
btnPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
btnPhoto.setFocusable(true);
btnPhoto.setFocusableInTouchMode(true);
btnPhoto.requestFocus();
btnPhoto.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_VOLUME_UP == keyCode) {
doFoo();
return true;
}
return false;
}
});
This code is placed in the onCreateView part of my fragment. Using debug, the event is never fired when I launch KeyEvent from ADB or use the hardware keys of my phone (volume keys).
public static class MyFragment extends Fragment {
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//YOUR CODE
return false;
}
});
}
}

How do I disable my Seekbar in Android with a Switch?

I want to disable my Seekbar and buttons with a switch which is Powerswitch
Here is a code snippet:
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
String sval = String.valueOf(i);
speakerVal.setText(sval);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// button - Favorite Channel ABC
cabc = (Button) findViewById(R.id.buttonABC);
cabc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set Favorite
curChannel.setText("007");
}
});
and here is my switch code:
final Switch switch1 = (Switch) findViewById(R.id.switch1);
switch1.setOnCheckedChangeListener(this);
more switch code:
public void onSwitchClicked(View view) {
final TextView PowerSwitch = (TextView) findViewById(R.id.PwrSwitchVal);
Switch sw = (Switch) view;
if (sw.isChecked()) {
PowerSwitch.setText("ON");
pwr = true;
} else {
PowerSwitch.setText("OFF");
pwr = false;
}
}
I know I can use the switch.isChecked(), but when I change the seekba1.setEnabled(false), I can't seem to get it to turn back on.
I haven't even tried to disable the buttons yet.
any help would be appreciated.
In your onSwitchClicked method, you should be calling seekbar.setEnabled in the if checked if-else statement. If checked seekbar.setEnabled(true) else seekbar.setEnabled(false)
try this.
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
if (arg1) {
seekbar1.setEnabled(true);
}
else{
seekbar1.setEnabled(false);
}
}
});

Onclick event on textview(that has TextIsSelectable="true") is ony called on second click

I have a onClickListener on a textview and the textview has the flag that it's selectable.
But the onclick event I specified is only called when the textview is clicked a second time.
After the second time it calles the onclick right, but if a other textview that also is selectable with a onclicklistener it also is only called the second time, then it works fine, but then the other one works only the second time again. I can't find the source of these weird events.
telefoonTXT.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {startTelIntent();}}
);
urlTXT.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {startWebIntent();}
});
I faced this issue as well. Whenever text view is touched firstly onTouch, then OnSelection and at last OnClick is called.
If i understand your problem clearly you want to select text in text view when user double taps or long presses like the usual text selection but when user simply clicks it once u want the onClick to function. I think the following might help you.
Add a gestureDetector to your text View.
GestureDetectorCompat mDetector;
mDetector = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener());
mDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// This is where u add your OnClick event
startTelIntent();
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
Log.d("dtttt", "double tap");
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
});
telefoonTXT.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mDetector.onTouchEvent(event);
return false;
}
});
In my case focus change listener works, but be aware for cases when you use it in androidTv that you move with D-pad
textView.setOnFocusChangeListener { v, hasFocus ->
if (hasFocus && textView.measuredHeight > textView.lineHeight * textView.lineCount) {
//your click event
}
}
I check if text can be scrolled then don't take the click event
The accepted answer is good. But I had one additional issue with it: When I have some selection text in textview, I want to tap on textview to only deselecting the text - without perfoming on click listener. And perform on click only with no text selection.
So below is my solution:
#SuppressLint("ClickableViewAccessibility")
public static void setOnClickGestureDetectorListener(TextView textView, Context context, View.OnClickListener onClickListener){
if (textView == null || context == null || onClickListener == null)){
return;
}
final GestureDetectorCompat detector = new GestureDetectorCompat(context, new GestureDetector.SimpleOnGestureListener());
detector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
onClickListener.onClick(textView);
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
});
textView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if ( v instanceof TextView ) {
TextView textView = (TextView)v;
if (textView.getSelectionStart() >= 0 && textView.getSelectionEnd() > textView.getSelectionStart()){
return false;
}
detector.onTouchEvent(event);
}
return false;
}
});
}
And calling example is below:
setOnClickGestureDetectorListener(textView, getContext(), new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is where u add your OnClick event
}
});
set this ...
TextisSelectable = "false"
i think it will be work correctly

Getting Data from EditText, RadioButton and Spinner

I search on many websites and many tutorials how can I get the data from editText and radioGroup and spinner DIRECTLY When the user input the data
I tried with this:
MyEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
{case1.setName(CaseName.getText().toString());
}
return true;
}
return false;
}
});
but it didn't take the data, I just use button to make that as shown below:
Test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.cancel1:
try
{
// 1-Name
case1.setName(CaseName.getText().toString());
}catch(Exception e){
}
break;
}
}});
Can anyone explain what shall I use to save the data in Object(case1) directly when the user input it ?
editext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// s is your text .
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
})
for Radio button
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show();
}
}
});

Categories

Resources