get selection handles programmatically in android - android

In my app I have EditText element but I use it like TextView (it is not editable).
I want to select all text in this field by click on some button.
I do it with the next code
Selection.setSelection((Spannable) et.getText(),0, et.getText().length());
et.setSelected(true);
It works fine and text selected but after that I can not change ends of selection.
How can I call selection handles programmatically?
Also I blocked OnLongClick because I need only Copy option and add it in custom button.

You need to make sure that the EditText has the property android:textIsSelectable="true" in the layout file.
You can also do the same thing by
et.setTextIsSelectable(true);
But please make sure that your application's minSdkVersion is 11 to use this.

Try some thing like this
et.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int strt= et.getSelectionStart();
int end = et.getSelectionEnd();
Log.i(" Selectionm",et.getText().toString().substring(strt, end));
return false;
}
});

With required android:textIsSelectable="true", call the following method with EditText or TextView as parameter:
private fun forceSelectionWithHandlesVisible(view: TextView) {
if (!view.hasSelection()) {
view.performLongClick()
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
// Hack required to make the selection handles visible when focus programmatically
val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_UP, 0F, 0F, 0)
with(event) {
view.onTouchEvent(this)
recycle()
}
}
}
Worked for me.

Related

Adding a swipe listener to textView in Anko

I'm looking to add swipe detection to a textView. I'm using Anko with Kotlin, and when it comes to setting up the textView, I'm able to specify an onClick event, but when I try to add an onTouch or any other gesture, it seems to fail for me (the fix-it just alternates between telling me to put stuff in parentheses and take it out again). I've included the code below and would appreciate any help!
relativeLayout{
//Title
var title = textView{
text = "Title Name"
textSize = 24f
onClick{
if(caller.returnedData != ""){
startActivity<MainActivity>()
}
}
onTouch {
// code to recognise touch here
}
}.lparams{
centerHorizontally()
topMargin = dip(180)
}
With Anko it's easy like a sharm:
onTouch { view, event ->
// .. Respond to touch events
// put return value at the end:
true // or view.onTouchEvent(event) to proceed other events
}
It's equal to the following Java code:
myView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// ... Respond to touch events
return true;
}
});

In EditText, popup a dialog when clicking on specific subset of text

Found two solutions - please see selected answer
When the user clicks in a certain region of an EditText, I want to popup a dialog. I used onClick to capture the click. This partially works: the first time the user taps the EditText, the soft keyboard pops up and the dialog doesn't. Subsequent taps bring up the keyboard and then the dialog (and the keyboard disappears).
I suspect this has something to do with the EditText gaining focus.
Here's a code snip:
public class PrefixEditText extends EditText implements TextWatcher, OnClickListener
{
public PrefixEditText (Context context)
{
super (context);
setOnClickListener (this);
}
#Override
public void onClick(View v)
{
int selStart = getSelectionStart();
if (selStart < some_particular_pos)
bring_up_dialog();
}
}
IMPORTANT: I don't want to completely disable the normal EditText behavior. I want the user to be able to make region selections (for copy & paste). I probably still want it to gain focus (so I don't break the model when people with physical keyboards use the app). And it's ok for the click to set the cursor position. Thus, solutions that override onTouch and block all onTouch actions from the EditText will not work for me.
UPDATE I've discovered a bit more. If the EditText is gaining focus, onFocusChange gets called and onClick does not. If it already has focus, onClick gets called and onFocusChange does not.
Secondly, it's possible to hide the keyboard by calling
setInputType (InputType.TYPE_NULL);
Doing so in onFocusChange works - the keyboard never shows up. Doing so in onClick (assuming the keyboard was hidden before the click) apparently is too late - the keyboard shows up and then disappears.
The next idea to try would be to hide the keyboard during onTouch. However, I'm afraid to mess with that code - seems that whatever I figure out would be very fragile with respect to future versions of EditText.
Any thoughs on this?
May be this can work
EditText e = new EditText(context);
e.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus)
{
//dialogue popup
}
}
});
or u can use e.hasFocus(); and then use e.setFocusable(false); to make it unfocus
/////////////// my code
e.setInputType(InputType.TYPE_NULL);
e.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder sa = new Builder(ctx);
sa.create().setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
e.setInputType(InputType.TYPE_CLASS_TEXT);
}
});
sa.show();
}
});
try change capture click by onClick to onTouch
this.editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//dialogue popup
}
return false;
}
});
try this if it can help u.first time the edittext will behave as a normal editttext and on condition u can show the dialog as needed
EditText editText;
mTim_edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
//statement
if(condition){
AlertDialog diaBox = Utils.showErrorDialogBox( "Term in Months Cannot be 0", context);
diaBox.show();
}
}
}
});
After lots of experiments, here are two working solutions! I tested them on my two devices - Nexus 7 running 4.2.1, Kyocera C5170 runing 4.0.4. My preference is Solution 2.
SOLUTION 1
For the first, the trick was to determine the cursor position in onTouch instead of onClick, before EditText has a chance to do it's work - particularly before it pops up the keyboard.
One additional comment: be sure to set android:windowSoftInputMode="stateHidden" in your manifest for the popup, or you'll get the keyboard along with the popup.
Here's the whole code:
public class ClickText extends EditText implements OnTouchListener
{
public ClickText (Context context, AttributeSet attrs)
{
super (context, attrs);
setOnTouchListener (this);
}
#Override
public boolean onTouch (View v, MotionEvent event)
{
if (event.getActionMasked() == MotionEvent.ACTION_DOWN)
{
int line = getLayout().getLineForVertical ((int)event.getY());
int onTouchCursorPos = getLayout().getOffsetForHorizontal (line, event.getX());
if (onTouchCursorPos < 10) // or whatever condition
showPopup (this); // or whatever you want to do
}
return false;
}
private void showPopup (final EditText text)
{
Intent intent = new Intent (getContext(), Popup.class);
((Activity)getContext()).startActivity (intent);
}
}
SOLUTION 2
This one is actually simpler and, I think, is better - fewer side effects.
Here, the trick is to let EditText do all its click processing and then override it asynchronously. The gist is: wait for the touch to "let go" - MotionEvent.ACTION_UP - and then instead of doing your action right then, post a Runnable to the event queue and do your action there.
The whole code:
public class ClickText extends EditText implements OnTouchListener
{
public ClickText (Context context, AttributeSet attrs)
{
super (context, attrs);
setOnTouchListener (this);
}
#Override
public boolean onTouch (View v, MotionEvent event)
{
switch (event.getActionMasked())
{
case MotionEvent.ACTION_UP:
{
post (new Runnable ()
{
// Do this asynch so that EditText can finish setting the selectino.
#Override
public void run()
{
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
// If selStart is different than selEnd, user has highlighed an area of
// text; I chose to ignore the click when this happens.
if (selStart == selEnd)
if (selStart >= 0 && selStart < 10) // or whatever range you want
showPopup (this);
}
});
break;
}
}
return false;
}
private void showPopup (final EditText text)
{
Intent intent = new Intent (getContext(), Popup.class);
((Activity)getContext()).startActivity (intent);
}
}
use this below code snippet
this.editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//dialogue popup
}
return false;
}
});

Android: How disable EditText depending focus

I'm doing a app wich have two EditText. What I wanna do is, if you click on one and write on it, the other must erease anything It has and only shows the hint string. I'm triying doing it witha a check method that does:
if(celsius.isFocused()){
faren.setText(faren.getHint().toString());
}
if(faren.isFocused()){
celsius.setText(celsius.getHint().toString());
}
Then I call this method within the onCreate() method, but of course It only checks one time, and if use that checkMethod inside a loop, the app doesn't show anthing, It freezes. An suggestions?
Use the OnFocusChangeListener.
faren.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus)
celcius.setText(""); // This will automatically show the hint text
}
});

EditText focus in android

In my application when I click an EditText, I have to perform some logic. I have the code. But it is not going into the click method.
My code:
EditText des=(EditText)findViewById(R.id.desinc);
des.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
java.lang.System.out.println("Inside click");
EditText income=(EditText)findViewById(R.id.editText1);
// TODO Auto-generated method stub
String inc=income.getText().toString();
int indexOFdec = inc.indexOf(".");
java.lang.System.out.println("index="+indexOFdec);
if(indexOFdec==0)
{
java.lang.System.out.println("inside index");
income.setText(inc+".00");
}
}
});
What am I doing wrong? Help me.
Try overriding onTouch by setting up an onTouchListener in the same way as an onClickListener. Use this code as a reference.
EditText dateEdit = (EditText) findViewById(R.id.date);
date.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
//anything you want to do if user touches/ taps on the edittext box
}
return false;
}
});
UPDATE(why this behavior):
The first click event focuses the control, while the second click event actually fires the OnClickListener. If you disable touch-mode focus with the android:focusableInTouchMode View attribute, the OnClickListener should fire as expected.
You can also try this: set android:focusableInTouchMode="false" for your EditText box in the xml. See if it works with the existing code.
You should use OnFocusChangeListener()
Try clicking EditText twice because at first instance EditText gets focus and after that EditText's click event executes. So, if you want your code to execute on first click write your code for focus change of EditText using OnFocusChangeListener().

Disable keyboard on EditText

I'm doing a calculator.
So I made my own Buttons with numbers and functions.
The expression that has to be calculated, is in an EditText, because I want users can add numbers or functions also in the middle of the expression, so with the EditText I have the cursor. But I want to disable the Keyboard when users click on the EditText.
I found this example that it's ok for Android 2.3, but with ICS disable the Keyboard and also the cursor.
public class NoImeEditText extends EditText {
public NoImeEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onCheckIsTextEditor() {
return false;
}
}
And then I use this NoImeEditText in my XML file
<com.my.package.NoImeEditText
android:id="#+id/etMy"
....
/>
How I can make compatible this EditText with ICS???
Thanks.
Here is a website that will give you what you need
As a summary, it provides links to InputMethodManager and View from Android Developers. It will reference to the getWindowToken inside of View and hideSoftInputFromWindow() for InputMethodManager
A better answer is given in the link, hope this helps.
here is an example to consume the onTouch event:
editText_input_field.setOnTouchListener(otl);
private OnTouchListener otl = new OnTouchListener() {
public boolean onTouch (View v, MotionEvent event) {
return true; // the listener has consumed the event
}
};
Here is another example from the same website. This claims to work but seems like a bad idea since your EditBox is NULL it will be no longer an editor:
MyEditor.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
int inType = MyEditor.getInputType(); // backup the input type
MyEditor.setInputType(InputType.TYPE_NULL); // disable soft input
MyEditor.onTouchEvent(event); // call native handler
MyEditor.setInputType(inType); // restore input type
return true; // consume touch even
}
});
Hope this points you in the right direction
Below code is both for API >= 11 and API < 11. Cursor is still available.
/**
* Disable soft keyboard from appearing, use in conjunction with android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
* #param editText
*/
public static void disableSoftInputFromAppearing(EditText editText) {
if (Build.VERSION.SDK_INT >= 11) {
editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);
} else {
editText.setRawInputType(InputType.TYPE_NULL);
editText.setFocusable(true);
}
}
You can also use setShowSoftInputOnFocus(boolean) directly on API 21+ or through reflection on API 14+:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
} else {
try {
final Method method = EditText.class.getMethod(
"setShowSoftInputOnFocus"
, new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
} catch (Exception e) {
// ignore
}
}
Add below properties to the Edittext controller in the layout file
<Edittext
android:focusableInTouchMode="true"
android:cursorVisible="false"
android:focusable="false" />
I have been using this solution for while and it works fine for me.
editText.setShowSoftInputOnFocus(false);
try: android:editable="false" or android:inputType="none"
Disable the keyboard (API 11 to current)
This is the best answer I have found so far to disable the keyboard (and I have seen a lot of them).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(false);
} else { // API 11-20
editText.setTextIsSelectable(true);
}
There is no need to use reflection or set the InputType to null.
Re-enable the keyboard
Here is how you re-enable the keyboard if needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(true);
} else { // API 11-20
editText.setTextIsSelectable(false);
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setClickable(true);
editText.setLongClickable(true);
editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
}
See this Q&A for why the complicated pre API 21 version is needed to undo setTextIsSelectable(true):
How to enable keyboard on touch after disabling it with setTextIsSelectable
This answer needs to be more thoroughly tested.
I have tested the setShowSoftInputOnFocus on higher API devices, but after #androiddeveloper's comment below, I see that this needs to be more thoroughly tested.
Here is some cut-and-paste code to help test this answer. If you can confirm that it does or doesn't work for API 11 to 20, please leave a comment. I don't have any API 11-20 devices and my emulator is having problems.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:background="#android:color/white">
<EditText
android:id="#+id/editText"
android:textColor="#android:color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:text="enable keyboard"
android:onClick="enableButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="disable keyboard"
android:onClick="disableButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
}
// when keyboard is hidden it should appear when editText is clicked
public void enableButtonClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(true);
} else { // API 11-20
editText.setTextIsSelectable(false);
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setClickable(true);
editText.setLongClickable(true);
editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
}
}
// when keyboard is hidden it shouldn't respond when editText is clicked
public void disableButtonClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
editText.setShowSoftInputOnFocus(false);
} else { // API 11-20
editText.setTextIsSelectable(true);
}
}
}
Gathering solutions from multiple places here on StackOverflow, I think the next one sums it up:
If you don't need the keyboard to be shown anywhere on your activity, you can simply use the next flags which are used for dialogs (got from here) :
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
If you don't want it only for a specific EditText, you can use this (got from here) :
public static boolean disableKeyboardForEditText(#NonNull EditText editText) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
editText.setShowSoftInputOnFocus(false);
return true;
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
try {
final Method method = EditText.class.getMethod("setShowSoftInputOnFocus", new Class[]{boolean.class});
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
try {
Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
method.setAccessible(true);
method.invoke(editText, false);
return true;
} catch (Exception ignored) {
}
return false;
}
Or this (taken from here) :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
editText.setShowSoftInputOnFocus(false);
else
editText.setTextIsSelectable(true);
To add to Alex Kucherenko solution: the issue with the cursor getting disappearing after calling setInputType(0) is due to a framework bug on ICS (and JB).
The bug is documented here: https://code.google.com/p/android/issues/detail?id=27609.
To workaround this, call setRawInputType(InputType.TYPE_CLASS_TEXT) right after the setInputType call.
To stop the keyboard from appearing, just override OnTouchListener of the EditText and return true (swallowing the touch event):
ed.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
The reasons for the cursor appearing on GB devices and not on ICS+ had me tearing my hair out for a couple of hours, so I hope this saves someone's time.
I found this solution which works for me. It also places the cursor, when clicked on EditText at the correct position.
EditText editText = (EditText)findViewById(R.id.edit_mine);
// set OnTouchListener to consume the touch event
editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event); // handle the event first
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // hide the soft keyboard
}
return true;
}
});
// only if you completely want to disable keyboard for
// that particular edit text
your_edit_text = (EditText) findViewById(R.id.editText_1);
your_edit_text.setInputType(InputType.TYPE_NULL);
Just set:
NoImeEditText.setInputType(0);
or in the constructor:
public NoImeEditText(Context context, AttributeSet attrs) {
super(context, attrs);
setInputType(0);
}
This worked for me.
First add this android:windowSoftInputMode="stateHidden" in your android manifest file, under your activity. like below:
<activity ... android:windowSoftInputMode="stateHidden">
Then on onCreate method of youractivity, add the foloowing code:
EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.onTouchEvent(event);
InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethod!= null) {
inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return true;
}
});
Then if you want the pointer to be visible add this on your xml android:textIsSelectable="true".
This will make the pointer visible.
In this way the keyboard will not popup when your activity starts and also will be hidden when you click on the edittext.
Just put this line inside the activity tag in manifest
android:windowSoftInputMode="stateHidden"
In my case, these lines work for me...
android:inputType="none"
android:focusableInTouchMode="true"
android:cursorVisible="false"
android:focusable="false"
before adding these lines, When I clicked on editText default keyboard showed/invoked.
After adding these lines keyboard was not displayed.
One way to disable keyboard on EditText is
binding.InputTextView.showSoftInputOnFocus = false
For Edit Text use the attribute android:focusable="false"
I donĀ“t know if this answer is the better, but i found a possible faster solution. On XML, just put on EditText this attributes:
android:focusable="true"
android:focusableInTouchMode="false"
And then do what you need with onClickListener.

Categories

Resources