Updating TextView on keyDown? - java

I am trying to update a TextView which will show the system volume. I have managed to capture the current system volume and display it, but it doesn't update when the volume is turned up/down (obviously).
I know there is an easy solution somewhere I just cant think! onKeyListeners?
I am now using this but it doesnt work:
TextView sysVol = (TextView)findViewById(R.id.systemVolume);
sysVol.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
//system volume
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int i = curVolume * 4;
String aString = Integer.toString(i);
TextView sysVol = (TextView)findViewById(R.id.systemVolume);
sysVol.setText(aString);
return true;
}
return false;
}
});

Well, the pseudo approach would be the following scenario:
1) Attach a listener to the view
2) Filter the different events in the callback
3) Update the TextView upon the (event==volume_up OR event==volume_down)
Basically, you'd want to implement the View.onKey()-method for this to be a minor bump in the road, instead of the current roadblock-state.
Summary: Add the following snippet to your code (some modification needed)
public YourClassHere extends SomethingCool implements OnKeyListener /*<-- important part*/
{
public boolean onKey(View v) {
// do something when the selected button is pushed
return true;
}
}

I think the problem is that the textview is not refreshing after you have changed the text. Try putting sysVol.requestLayout() after you changed the text to refresh the textview. Also, I don't think you are suppose to put return false after the closing bracket of the onKey() method.

Related

Layout doesn't scroll up when next edittext entered

I have searched a lot for a solution but nothing works.
Update: post at bottom
I have a ScrollView and a FrameLayout as child.
Then I set up some EditText programmatically with LayoutParams.
Furthermore, I activated the ime options, so it will go to the next Edittext automatically.
When it now goes to the next one, the layout doesn't scroll up and the keyboard hides the EditText.
Answers like android:windowSoftInputMode="adjustPan / adjustResize"
didn't work.
I also tried to scroll manually with
Spieler1.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
int current_pos = scroll2.getScrollY();
scroll2.smoothScrollTo(0,(int)(current_pos + height/4));
scroll2.post(new Runnable() {
#Override
public void run() {
Spieler2.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
});
return true;
}
return false;
}
});
Strange things happened: It wanted to scroll up, but then suddenly goes back to the original position covering the EditText.
I have no idea, why it doesn't scsroll up, but maybe you have.
Thanks for answering.
I suspect the smoothScrollTo() call causes the behavior you've seen. You might want to use the android:nextFocusDown attribute for your first EditText instead of setting the OnKeyListener.

show and hide password using drawable icons in android

I have designed a screen with password field using EditText, in the EditText I am using drawableRightIcon which has to show the password visible when we click the drawable button and also replace that drawable icon with another icon? can anyone help please?
Following is the code that I'm using currently in my apps for this purpose. We basically put a touch listener to our EditText and identify if the click occurred on the drawable and act accordingly (also switching icons):
getPasswordEditText().setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_RIGHT = 2; // index
if (event.getAction() == MotionEvent.ACTION_UP) {
if (event.getRawX() >= (getPasswordEditText().getRight() - getPasswordEditText().getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
if (passwordShown) {
passwordShown = false;
// 129 is obtained by bitwise ORing InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
getPasswordEditText().setInputType(129);
// Need to call following as the font is changed to mono-space by default for password fields
getPasswordEditText().setTypeface(Typeface.SANS_SERIF);
getPasswordEditText().setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.locked_icon, 0);
} else {
passwordShown = true;
getPasswordEditText().setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
getPasswordEditText().setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.unlocked_icon, 0);
}
return true;
}
}
return false;
}
});
Execute the following statements when your image button is clicked
String password= your_editText.getText().toString().trim();
your_editText.setText(password);
your_imgview.setImageResource(R.drawable.new_image)
Use the following code to show and hide the password. You can use an ImageView beside the check box.
Used a checkbox (you can use a image button also instead of it using the same concept except that you have to use an onCLickListener instead).
loginShowHidePassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// EditText loses the cursor position when you change the InputType
int curPos = mPasswordView.getSelectionStart();
if (isChecked) {
mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
imageview.setImageResource(R.drawable.newImage);
} else {
mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
loginShowHidePassword.setImageResource(R.drawable.newImage);
}
mPasswordView.setSelection(curPos);
}
});
You need to save a new a new image named newImage in drawable.
mPasswordView is the password EditText

How to avoid Default selection on long press in android Kitkat 4.4?

Hello Developers,
i am working with Btwebview here on long press we are avoiding the default selection functionality on long press and giving our own.The overriding of long press method is working perfectly till android 4.3 but with 4.4 the defalut selection also coming with actionbar.Below i am mentioning the sample code-
public class BTWebView extends WebView implements TextSelectionJavascriptInterfaceListener, OnTouchListener, OnLongClickListener,DragListener {
.......
public BTWebView(Context context) {
super(context);
this.ctx = context;
this.setup(context);
}
protected void setup(Context context)
{
this.setOnLongClickListener(this);
this.setOnTouchListener(this);
}
and on long press
#Override
public boolean onLongClick(View v)
{
......
return true;
}
}
Here after overriding the long click and return value as true so it avoid default selection till 4.3 so please tell me how to avoid either the complete default selection or atleast avoid the action bar comes on long press .thanks in advance
i found the solution for this question here on github ,it is-
if(event.getAction() == MotionEvent.ACTION_UP)
{
if(!mScrolling){
mScrolling = false;
endSelectionMode();
return false;
}
mScrollDiffX = 0;
mScrollDiffY = 0;
mScrolling = false;
// Fixes 4.4 double selection
return true;
}
here also you have to return the true,after that the default selection will not come .
The solution for KitKat and above proposed by Ravi Saini works to prevent the default selection interface to appear. However, return true for ACTION_UP event prevents fling gestures for scrolling the contents vertically quickly, so the use of WebView seems unnatural. I added isInSelectionMode() condition to prevent this, now fling gestures work fine, except when in selection mode. The code from WebViewMarker GitHub project with my change is as follows (in TextSelectionSupport.java module, onTouch() method):
case MotionEvent.ACTION_UP:
if (!mScrolling) {
endSelectionMode();
//
// Fixes 4.4 double selection
// See: http://stackoverflow.com/questions/20391783/how-to-avoid-default-selection-on-long-press-in-android-kitkat-4-4
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
return false;
}
}
mScrollDiffX = 0;
mScrollDiffY = 0;
mScrolling = false;
//
// Fixes 4.4 double selection
// See: http://stackoverflow.com/questions/20391783/how-to-avoid-default-selection-on-long-press-in-android-kitkat-4-4
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isInSelectionMode()) {
return true;
}
break;
Greg
If the onLongClick() method isn't getting called and the long press in the WebView is enabling the user selection (i.e. copy, cut, paste etc) then you could try the user-select CSS property
user-select:none;
Which will surpress that behaviour, although not sure if this will still fire the long click listener, or whether the WebView will continue to inherit the click events.

Implementing Search Button on my Keyboard

I'm trying to implement a search button in place of the regular enter button on my inbuilt android keyboard. I tried doing:
resultView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
System.out.println("You searched for this!");
return true;
}
return false;
}
But the regular 'enter' button is still appearing. I do not want to use XML and i'm creating my UI completely on JAVA. What should i do? Help would be appreciated. Thanks!
EditText view = new EditText(this);
view.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
view.setSingleLine(true);
And you are good to go, you set SingleLine attribute to change the new line button "default behavior in multi-line editext" to search button .
Sounds like you need to set the imeOptions programmatically. Try something like this:
editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
You might have to play around with the available options to get exactly what you want.

How to send key event to an edit text

For example, send a backspace key to the edit text control to remove a character or send a char code like 112 to append a character in the edittext control programmatically.
Actually, I need a method like
void onKeyReceived(int keyCode)
{
// here I would like to append the keyCode to EditText, I know how to add a visible character, but what about some special keys, like arrow key, backspace key.
}
To send a simulated backspace key press to an EditText you have to send both key press and release events. Like this:
mEditText.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_DEL, 0));
mEditText.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_DEL, 0));
This can be used to send any other key code, not just delete.
Your question is not all that clear, but I think you want to modify/append text to a TextView when certain buttons are pressed. If so, you want a combination of some of the existing answers.
#Override
public void onCreate(Bundle savedInstanceState) {
...
(TextView) textView = (TextView) findViewById(R.id.myTextView);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
// user pressed the "BACK" key. Append "_back" to the text
textView.append("_back");
return true;
case KeyEvent.KEYCODE_DEL:
// user pressed the "BACKSPACE" key. Append "_del" to the text
textView.append("_del");
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
Whether to return true for each case you have handled (as above) or to always return super.onKeyDown(keyCode, event); after your switch statement will depend on your exact requirements. Check the documentation for the behaviour of onKeyDown
If, instead of appending text in each case you want to delete a character, or move the cursor, you could do that in each case statement. Have a look at the TextView documentation for the different methods you can call. Also look at the KeyEvent documentation for a list of the keys you can check for.
I think you need use addTextChangedListener to EditText.
Refer the answer of EditText input with pattern android and Live editing of users input
virsir , I suppose you are looking for dispatching hard keys programmatically.
For that you may try dispatch (KeyEvent.Callback receiver, KeyEvent.DispatcherState state, Object target) with an example at Back and other hard keys: three stories
Hope that helps.
Check for key events in your activity. for example, this code listens for back keypress:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
just use the setText method to do this. If you are wanting to simulate a backspace you could do something like this.
String curText = mEditText.getText();
if(!curText.equals("")){
mEditText.setText(curText.subString(0, curText.length - 1));
}
to simulate backspace key, just ad code
editText.setText(editText.getText().substring(0,editText.getText().length()-1))
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
to simulate adding a character, put the code
editText.setText(editText.getText() + (char) charCode)
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
Take a look at this article: creating-input-method.html. Basically, you can either manually send KeyEvents or you can manually edit and commit text around the cursor in the application's Input View.These are all done via your IME's InputConnection.
Hope this helps,
if you want a click listener, the best way to do it is this:
View textfield = findViewById(R.id.textfield);
textfield .setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/*your code for the click event here*/ }});
if you want a backspace button, do this:
public void backSpace() {
EditText textfield = (EditText)findViewById(R.id.textfield);
try {
textfield.getText().delete(textfield.getSelectionEnd() - 1, textfield.getSelectionStart());
} catch (Exception e) {
try {
textfield.getText().delete(textfield.length() - 1, textfield.length());
} catch (Exception myException) {
//textfield.getText().delete(textfield.length(), textfield.length() - 1);
}
}
}
if you want to append a character in the EditText, do this:
EditText textfield = (EditText)findViewById(R.id.textfield);
textfield.setText(textfield.getText().concat("112"));
try implementing TextWatcher interface.
it has 3 methods which you need to override.
public void afterTextChanged(Editable s) {
Log.v("afterTextChanged","here");
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Log.v("beforeTextChanged","here");
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
I think this will work.

Categories