Implementing onKeyPreIme(int keyCode, KeyEvent event) in Fragment - android

I cannot figure how to implement onKeyPreIme(int keyCode, KeyEvent event) in a Fragment.
#Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK &&
event.getAction() == KeyEvent.ACTION_UP) {
// do your stuff
return false;
}
return super.dispatchKeyEvent(event);
}
I tried a lot but nothing works. Also, I could not find anything on Google or Stack Overflow. I would like to perform an action when the back key is pressed and the softkeyboard is up. Setting an onKeyListener on my EditTexts did not work, since KeyEvent.KEYCODE_BACK is not called when the soft keyboard is up. I appreciate any help and source code.

I was able to implement onKeyPreIme by sub-classing my EditText views that were related to the keyboard input. The goal is to make a custom lock screen that the user must enter a pass code or leave the application. When the user taps the "keyboard down" button the keyboard does not disappear.
Make sure to create a separate .java file for the subclassed EditText. Additionally, be sure to use the constructor in the code below (must pass AttrubuteSet).
I realize that my implementation of onKeyPreIme may not match yours, however it does demonstrate how to intercept the keyboard events before the InputMethodManager does it's thing.
I hope this helps.
Screenshot UserLockActivity
EditText Subclass
public class LockEditText extends EditText {
/* Must use this constructor in order for the layout files to instantiate the class properly */
public LockEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
// TODO Auto-generated constructor stub
}
#Override
public boolean onKeyPreIme (int keyCode, KeyEvent event)
{
// Return true if I handle the event:
// In my case i want the keyboard to not be dismissible so i simply return true
// Other people might want to handle the event differently
System.out.println("onKeyPreIme " +event);
return true;
}
}
UserLockActivity.java
public class UserLockActivity extends Activity
{
private LockEditText editText1;
private LockEditText editText2;
private LockEditText editText3;
private LockEditText editText4;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_lock);
editText1 = (LockEditText) findViewById(R.id.lock_text_1);
editText2 = (LockEditText) findViewById(R.id.lock_text_2);
editText3 = (LockEditText) findViewById(R.id.lock_text_3);
editText4 = (LockEditText) findViewById(R.id.lock_text_4);
setupTextChangedListener(editText1);
setupTextChangedListener(editText2);
setupTextChangedListener(editText3);
setupTextChangedListener(editText4);
// A method to bring out the keyboard when the view appears
setFocusOnEditText(editText1);
}
public void setFocusOnEditText(LockEditText editText)
{
editText.clearFocus();
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}
public void setupTextChangedListener(LockEditText editText)
{
editText.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3)
{
// TODO Auto-generated method stub
}
});
}
}
activity_user_lock.xml Layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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"
tools:context=".UserLockActivity" >
<TextView
android:id="#+id/main_lock_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:paddingTop="60dp"
android:paddingBottom="20dp"
android:text="#string/enter_passcode"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:id="#+id/lock_input_layout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/main_lock_text"
android:orientation="horizontal" >
<com.yourpackage.yourappname.LockEditText
android:id="#+id/lock_text_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:ems="10"
android:inputType="numberPassword"
android:textSize="30sp"
android:gravity="center_horizontal"
android:textStyle="bold" >
</com.yourpackage.yourappname.LockEditText>
<com.yourpackage.yourappname.LockEditText
android:id="#+id/lock_text_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:ems="10"
android:inputType="numberPassword"
android:textSize="30sp"
android:gravity="center_horizontal"
android:textStyle="bold" >
</com.yourpackage.yourappname.LockEditText>
<com.yourpackage.yourappname.LockEditText
android:id="#+id/lock_text_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:ems="10"
android:inputType="numberPassword"
android:textSize="30sp"
android:gravity="center_horizontal"
android:textStyle="bold">
</com.yourpackage.yourappname.LockEditText>
<com.yourpackage.yourappname.LockEditText
android:id="#+id/lock_text_4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:ems="10"
android:inputType="numberPassword"
android:textSize="30sp"
android:gravity="center_horizontal"
android:textStyle="bold" >
</com.yourpackage.yourappname.LockEditText>
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/lock_input_layout"
android:layout_centerHorizontal="true"
android:text="text" />
</RelativeLayout>

This is my solution and it works really well for me, but everyones needs are different.
First i subclassed EditText and hooked up a listener (Google should make this the default)
public class ListenerEditText extends EditText {
private KeyImeChange keyImeChangeListener;
public ListenerEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setKeyImeChangeListener(KeyImeChange listener){
keyImeChangeListener = listener;
}
public interface KeyImeChange {
public void onKeyIme(int keyCode, KeyEvent event);
}
#Override
public boolean onKeyPreIme (int keyCode, KeyEvent event){
if(keyImeChangeListener != null){
keyImeChangeListener.onKeyIme(keyCode, event);
}
return false;
}
}
Then you can attach a listener from anywhere like so:
myListenerEditText.setKeyImeChangeListener(new KeyImeChange() {
#Override
public void onKeyIme(int keyCode, KeyEvent event) {
// All keypresses with the keyboard open will come through here!
// You could also bubble up the true/false if you wanted
// to disable propagation.
}
});

I was not able to figure out how to implement the onKeyPreIME, but I was able to perform an action after the keyboard disappeared with the following code:
You man need to change comparison heightDiff > 200. This comparison worked for me because I had a scrollview.
fragmentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if(getView() != null){
int heightDiff = getView().getRootView().getHeight() - getView().getHeight();
if (heightDiff < 200) {
rlupdate.setVisibility(RelativeLayout.VISIBLE);
}
else {
rlupdate.setVisibility(RelativeLayout.GONE);
}
}
}
});

this is a more full code of answer by Deminetix.
i have used the answer by Deminetix to filter handheld barcode reader on android and have the result.
to make it usable on a screen only with buttons i have added a EditText with android:textColor="#FF000000" android:background="#00FFFFFF" android:enabled="false"
disabled EditText still gets keyboard events.
optionally i could hide the software keyboard using the following but after disabling the EditText it was not required.
//InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//imm.showSoftInput(textPatientId, InputMethodManager.HIDE_IMPLICIT_ONLY);
MainActivity.java:
package com.doodkin.keyboardtest;
import com.doodkin.keyboardtest.ListenerEditText.KeyImeChange;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
public class MainActivity extends Activity {
private static final String TAG = "keyboard test";
//private EditText editText1;
ListenerEditText editText1=null;
public String barcodebuffer="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (ListenerEditText) findViewById(R.id.editText1);
editText1.setKeyImeChangeListener(new KeyImeChange() {
#Override
public boolean onKeyIme(int keyCode, KeyEvent event) {
String deviceName=event.getDevice().getName();
int keyboardType=event.getDevice().getKeyboardType();
int indexof=deviceName.indexOf("USB");
if(indexof!=-1 && keyboardType==InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC)
{
if(event.getKeyCode()==KeyEvent.KEYCODE_ENTER)
{
if(barcodebuffer!="")
{
Log.d(TAG, "filterBarcodeKeys Chars Flush: " + barcodebuffer );
barcodebuffer="";
}
}
else
{
barcodebuffer+=Character.toString((char)event.getUnicodeChar());
//Log.d(TAG, "filterBarcodeKeys Char: " + Character.toString((char)event.getUnicodeChar()) );
}
return true;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<com.doodkin.keyboardtest.ListenerEditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10" >
<requestFocus />
</com.doodkin.keyboardtest.ListenerEditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="69dp"
android:text="Button" />
</RelativeLayout>
ListenerEditText.java:
package com.doodkin.keyboardtest;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;
/*
* example:
myListenerEditText.setKeyImeChangeListener(new KeyImeChange() {
#Override
public boolean onKeyIme(int keyCode, KeyEvent event) {
// All keypresses with the keyboard open will come through here!
// You could also bubble up the true/false if you wanted
// to disable propagation.
}
});
*/
public class ListenerEditText extends EditText {
private KeyImeChange keyImeChangeListener;
public ListenerEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setKeyImeChangeListener(KeyImeChange listener){
keyImeChangeListener = listener;
}
public interface KeyImeChange {
public boolean onKeyIme(int keyCode, KeyEvent event);
}
#Override
public boolean onKeyPreIme (int keyCode, KeyEvent event){
if(keyImeChangeListener != null){
return keyImeChangeListener.onKeyIme(keyCode, event);
}
return false;
}
}

Related

How to pass value from a method to another method

import android.support.v4.app.Fragment;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.NumberPicker.OnValueChangeListener;
public class MainActivity extends Activity implements OnValueChangeListener {
EditText push_ups, sit_ups;
NumberPicker np;
Button calculate;
final Context context = this;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calculate = (Button)findViewById(R.id.calculate);
push_ups = (EditText)findViewById(R.id.pushups);
sit_ups = (EditText)findViewById(R.id.situps);
np = (NumberPicker)findViewById(R.id.np1);
checkbox = (CheckBox)findViewById(R.id.checkbox);
String[] values = {"some array"};
np.setMaxValue(values.length-1);
np.setMinValue(0);
np.setDisplayedValues(values);
np.setWrapSelectorWheel(false);
//calculateButton runs when I click the "calculate" Button
calculateButton();
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
}
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(push_ups.getWindowToken(), 0);
}
public int calculatePushups() {
int pushupScore = 0;
int ageGroup = Integer.parseInt(null, np.getValue());
int pushupReps = Integer.parseInt(push_ups.getText().toString());
final int [][] pushupTable = {"some 2D array"};
if (pushupReps<= 60) {
pushupScore = pushupTable[pushupReps][ageGroup];
} else {
pushupScore = 60;
}
return pushupScore;
}
public int calculateSitups() {
final int [][] situpTable = {"some 2D array"};
return 0;
}
private void normalRun() {
}
private void specialRun() {
}
private void calculateRun() {
if (checkbox.isChecked()) {
specialRun();
}
else {
normalRun();
}
}
private void calculateScore() {
calculatePushups();
calculateSitups();
calculateRun();
}
public void calculateButton() {
final TextView pus = (TextView)findViewById(R.id.pushup_score);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_custom);
dialog.setTitle("Score");
I am trying to set the TextView to display the pushupScore here but it seems I am trying to pass a result from another method to this. I have no idea how to get it around still new with android,
//pus.setText(pushupScore);
pus.setText(String.valueOf(calculatePushups()));
Button dialogButton = (Button) dialog.findViewById(R.id.dialog_ok);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
Here's my dialog XML code:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Push-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/pushup_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.97"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Sit-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="2.4km Run: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Award: "
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/dialog_ok"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:lineSpacingExtra="5dp"
android:text="Ok" />
</LinearLayout>
you are returning the pushupScore in calculatePushups so just write:
pus.setText(String.valueOf(calculatePushups()));
And btw this is not a android mechanism, this is simple java return usage:
http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
You left out quite a bit of your code so I'm not sure where your problem is, but if you could follow these steps and let me know if you're getting any errors etc? Anyway, here is what you need to have:
Make sure your Activity implements OnClickListener:
public class MainActivity extends Activity implements OnClickListener, OnValueChangeListener {
//...
}
Within the activity's overridden onCreate() method, register the activity as the handler:
calculate = (Button)v.findViewById(R.id.dialog_ok);
calculate.setOnClickListener(this);
Within MainActivity, have the handler like so:
public void onClick(View v){
switch(v.getId(){
case R.id.dialog_ok:
push_ups.setText("" + calculatePushups());
break;
}
// ...
}
Perhaps you should change your EditText into a TextView, the EditText isn't necessary and might be causing problems?
Is this what you were after?

Handling touch Events for all layouts in xml

I have a linear layout which contains 5 linear layouts as its child. I want to handle the touch event for each child linear layouts. My layout looks like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container">
<LinearLayout android:id="#+id/item1"
android:layout_width="match_parent"
style="#style/NavLinkItemContainer"
android:layout_height="wrap_content">
<TextView
style="#style/NaviLinkSelected"
android:text="First"/>
</LinearLayout>
<LinearLayout android:id="#+id/item2"
android:layout_width="match_parent"
style="#style/NavLinkItemContainer"
android:layout_height="wrap_content">
<TextView
style="#style/NaviLinks"
android:text="Second"/>
</LinearLayout>
<LinearLayout android:id="#+id/item3"
android:layout_width="match_parent"
style="#style/NavLinkItemContainer"
android:layout_height="wrap_content">
<TextView
style="#style/NaviLinks"
android:text="Third"/>
</LinearLayout>
<LinearLayout android:id="#+id/item4"
android:layout_width="match_parent"
style="#style/NavLinkItemContainer"
android:layout_height="wrap_content">
<TextView
style="#style/NaviLinks"
android:text="Fourth"/>
</LinearLayout>
<LinearLayout android:id="#+id/item5"
android:layout_width="match_parent"
style="#style/NavLinkItemContainer"
android:layout_height="wrap_content">
<TextView
style="#style/NaviLinks"
android:text="Fifth"/>
</LinearLayout>
</LinearLayout>
and My activity using the layout looks like
public class MainActivity extends Activity implements OnTouchListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("","ON TOUCH VIEW ######## "+v.getId());
return false;
}
}
When touching the child layouts, am not getting id(item1,item2...) in onTouch Event
Please advice.
For each layout you want to add touch listener, set onTouchListener.
for example,
LinearLayout l1 = (LinearLayout) findViewById(R.id.item2);
l1.setOntouchListener(this);
So for each ViewGroup you have to set the listener. The rest of things is already done by your. Int onTouch method you can handle touch or all ViewGroup
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.item2:
do something
break;
case R.id.item3:
do something
break;
default:
break;
}
// if you want to consume the behavior then return true else retur false
}
Here is a solution to add an OnTouchListener to every element in the constraint, which will hide the keyboard every time you touch something but an object in the exclusion list.
import android.content.Context;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatCallback;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ConstraintLayout constraintLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = findViewById(R.id.editText);
//Get current ViewGroup. Might have to add an id in the layout xml for the constraint.
constraintLayout = findViewById(R.id.constraint);
//List of items that should be excluded
ArrayList<Integer> listOfExclusion = new ArrayList<>();
listOfExclusion.add(editText.getId());
addTouchListeners(listOfExclusion, constraintLayout);
}
/**
* #param excludedResIds ArrayList of list of ids that should be excluded by the addTouchListener
* #param parent ViewGroup containing the elements you want to lose focus off.
*/
void addTouchListeners(ArrayList<Integer> excludedResIds, ViewGroup parent){
parent.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
constraintLayout.requestFocus();
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return false;
}
});
addTouchListener(excludedResIds,parent);
}
/**
* #param excludedResIds ArrayList of list of ids that should be excluded by the addTouchListener
* #param parent ViewGroup containing the elements you want to lose focus off.
*/
void addTouchListener(ArrayList<Integer> excludedResIds, ViewGroup parent)
{
for(int index = 0; index<parent.getChildCount(); ++index) {
View nextChild = parent.getChildAt(index);
try{
addTouchListener(excludedResIds, (ViewGroup) nextChild);
}catch (Exception e){
}
if(!excludedResIds.contains(nextChild.getId()))
nextChild.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
constraintLayout.requestFocus();
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return false;
}
});
}
}
}

Need number only soft keyboard?

Hi I need a soft keyboard with only numeric values 0 to 9 and Enter key. Shouldn't show anything other than these like . , ( ) etc...
I tried several options as suggested here but nothings seems to work for me.
setRawInputType(Configuration.KEYBOARD_QWERTY)
setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED)
setRawInputType(InputType.TYPE_CLASS_NUMBER)
setRawInputType(InputType.TYPE_CLASS_PHONE)
I always have the extra characters show up on the keyboard like:
setRawInputType(Configuration.KEYBOARD_12KEY) shows a keyboard like this:
Would appreciate any help. Thanks in advance.
NOTE:
android:minSdkVersion="14": ICS4.0
android:targetSdkVersion="17": JB 4.2
All you can do for standard keyboards is suggest input types. The keyboard can still display or not display whatever keys it wants. If you must have certain keys and only those, you need to create a custom soft keyboard. If it's only for your app, and especially if it's only for one activity, I wouldn't actually implement a standard keyboard, but just use views/buttons that do the appropriate actions.
I've faced the same problem , and i found tat there is no android keyboard like this available
and that the only way is to implement your own.
so i would like to share with you my implement and hopefully save you some valuable time:
i've created this xml , you can modify the colors,fonts and the size of the keyboard accourding to your needs:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<LinearLayout
android:id="#+id/one_to_three"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/one_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1"
android:textSize="25sp" />
<Button
android:id="#+id/two_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="2"
android:textSize="25sp" />
<Button
android:id="#+id/three_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="3"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/four_to_six"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/one_to_three"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/four_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4"
android:textSize="25sp" />
<Button
android:id="#+id/five_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="5"
android:textSize="25sp" />
<Button
android:id="#+id/six_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="6"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/seven_to_nine"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/four_to_six"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/seven_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7"
android:textSize="25sp" />
<Button
android:id="#+id/eight_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="8"
android:textSize="25sp" />
<Button
android:id="#+id/nine_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="9"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/zero"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/seven_to_nine"
android:orientation="horizontal"
android:weightSum="3" >
<Button
android:id="#+id/zero_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="2"
android:text="0"
android:textSize="25sp" />
<Button
android:id="#+id/back_btn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Back"
android:textSize="25sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/done"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_below="#+id/zero"
android:orientation="horizontal" >
<Button
android:id="#+id/done_btn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Done"
android:textSize="30sp" />
</LinearLayout>
</RelativeLayout>
i've created this fragment:
package com.galrom.keyboard; //replace it with your package
import com.example.calculator.R;//import your own R class
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnLongClickListener;
import android.widget.Button;
public class KeyBoardFragment extends Fragment {
private Button one_btn;
private Button two_btn;
private Button three_btn;
private Button four_btn;
private Button five_btn;
private Button six_btn;
private Button seven_btn;
private Button eight_btn;
private Button nine_btn;
private Button zero_btn;
private Button back_btn;
private Button done_btn;
private StringBuilder sb;
private onKeyBoardEvent keyboardEventListener;
private int maxLength=10;
private int currentLength;
public static KeyBoardFragment newInstance(String EditTextValue)
{
KeyBoardFragment fragment=new KeyBoardFragment();
Bundle bundle=new Bundle();
bundle.putString("et_value", EditTextValue);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onAttach(Activity activity) {
try{
keyboardEventListener=(onKeyBoardEvent)activity;
}
catch(ClassCastException e)
{
Log.e("ClassCastException in KeyBoardFragment row 50",activity.toString()+" must implement onKeyboardEvent");
e.printStackTrace();
}
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
sb=new StringBuilder(getArguments().getString("et_value"));
currentLength=sb.length();
View rootView=inflater.inflate(R.layout.numeric_keyboard_layout, container, false);
one_btn=(Button)rootView.findViewById(R.id.one_btn);
one_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
add("1");
}
});
two_btn=(Button)rootView.findViewById(R.id.two_btn);
two_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("2");
}
});
three_btn=(Button)rootView.findViewById(R.id.three_btn);
three_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("3");
}
});
four_btn=(Button)rootView.findViewById(R.id.four_btn);
four_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("4");
}
});
five_btn=(Button)rootView.findViewById(R.id.five_btn);
five_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("5");
}
});
six_btn=(Button)rootView.findViewById(R.id.six_btn);
six_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("6");
}
});
seven_btn=(Button)rootView.findViewById(R.id.seven_btn);
seven_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("7");
}
});
eight_btn=(Button)rootView.findViewById(R.id.eight_btn);
eight_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("8");
}
});
nine_btn=(Button)rootView.findViewById(R.id.nine_btn);
nine_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add("9");
}
});
zero_btn=(Button)rootView.findViewById(R.id.zero_btn);
zero_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sb.length()>0)
add("0");
}
});
back_btn=(Button)rootView.findViewById(R.id.back_btn);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sb.length()>0)
{
currentLength--;
sb.deleteCharAt((sb.length())-1);
keyboardEventListener.backButtonPressed(sb.toString());
}
}
});
back_btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
currentLength=0;
sb=new StringBuilder();
keyboardEventListener.backLongPressed();
return false;
}
});
done_btn=(Button)rootView.findViewById(R.id.done_btn);
done_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyboardEventListener.doneButtonPressed(sb.toString());
}
});
return rootView;
}
public interface onKeyBoardEvent
{
public void numberIsPressed(String total);
public void doneButtonPressed(String total);
public void backLongPressed();
public void backButtonPressed(String total);
}
public int getMaxLength() {
return maxLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public void add(String num)
{
currentLength++;
if(currentLength<=maxLength)
{
sb.append(num);
keyboardEventListener.numberIsPressed(sb.toString());
}
else
currentLength--;
}
}
3.the effect of a poping keyboard under the EditText when it is pressed is achived by
creating an empty RelativeLayout that function as an container to the keyboard:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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"
tools:context=".MainActivity" >
<com.galrom.keyboard.EditTextNoKeyBoard
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Key_board_container"
android:layout_centerHorizontal="true"
android:clickable="true"
android:ems="10" />
<RelativeLayout
android:id="#+id/Key_board_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:background="#ffffff" >
</RelativeLayout>
when the user press on the EditText the we add the fragment to the container and when he presses done we hide it. the keyboard fragment comunicate with the Activity with the onKeyBoardEvent interace.
NOTE:the hosting activity must implement this interface or else a ClassCastException will be thown.
VERY IMPORTANT: i didn't handled the orientation change, if you change to ladscape while the keyboard is open it will crash, so either disable landscape mode or handle the orientation change to avoid a nullPointerException on the key_board_fragment.
this is the Activity that implemets the keyBoard:
package com.galrom.keyboard;
import com.example.calculator.R;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements KeyBoardFragment.onKeyBoardEvent{
private EditText et;
private KeyBoardFragment keyboard_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.editText1);
et.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(keyboard_fragment==null)
{
keyboard_fragment=KeyBoardFragment.newInstance(et.getText().toString());
getSupportFragmentManager().beginTransaction().add(R.id.Key_board_container, keyboard_fragment).commit();
}
else
{
if(keyboard_fragment.isVisible())
getSupportFragmentManager().beginTransaction().hide(keyboard_fragment).commit();
else
{
keyboard_fragment=KeyBoardFragment.newInstance(et.getText().toString());
getSupportFragmentManager().beginTransaction().add(R.id.Key_board_container, keyboard_fragment).commit();
}
}
});
}
#Override
public void numberIsPressed(String total) {
// TODO Auto-generated method stub
et.setText(total);
}
#Override
public void doneButtonPressed(String total) {
// TODO Auto-generated method stub
et.setText(total);
if(keyboard_fragment.isVisible())
getSupportFragmentManager().beginTransaction().hide(keyboard_fragment).commit();
}
#Override
public void backLongPressed() {
// TODO Auto-generated method stub
et.setText("");
}
#Override
public void backButtonPressed(String total) {
// TODO Auto-generated method stub
et.setText(total);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(keyboard_fragment!=null)
{
if(keyboard_fragment.isVisible())
getSupportFragmentManager().beginTransaction().remove(keyboard_fragment).commit();
else
super.onBackPressed();
}
else
super.onBackPressed();
}
}
and the last thing:
to disable the poping of the standart keyboard of android i've created an CustomEditText that simply returns false at: onCheckIsTextEditor() , this is the CustomEditText class:
package com.galrom.keyboard;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
public class EditTextNoKeyBoard extends EditText {
public EditTextNoKeyBoard(Context context) {
super(context);
}
public EditTextNoKeyBoard(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EditTextNoKeyBoard(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onCheckIsTextEditor() {
// TODO Auto-generated method stub
return false;
}
}
Hope it helped you out...
if you have suggestions for improvement i will be happy to hear.
Gal.
In addition to it set inputType="phone" on the EditText. That will open numeric pad keyboard once you start typing however it will include all extra characters related to the numbers. You would need to implement your own keyboard to keep only the numeric values.
This solution uses numberPassword by overriding the default transformation method for the EditText to show characters instead of dots.
<EditText
android:id="#+id/userid"
android:inputType="numberPassword"
android:maxLength="6"
/>
Add to OnCreate.
// Numeric 6 character user id
EditText input = findViewById(R.id.userid);
// Process input and show characters instead of dots
input.setTransformationMethod(SingleLineTransformationMethod.getInstance());
By default based on your device, the keyboard shows the special characters too in number keyboard . specifying the Keyboard type for the Text field you can achieve the expected result,such as
InputFieldName.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
i.e.
If you need only number included with special characters,then you can use
InputType.TYPE_CLASS_NUMBER
or
if you need to exclude those special characters too then use InputType.TYPE_NUMBER_VARIATION_PASSWORD
i have had the same problem that you have, and just came with a solution, perhaps its not elegant, nor its easy, but it does work splendid...
First of all, the only InputType that works with that keyboard (at least until 4.3) is "numberPassword", but this "hides" your input as dots. so i used that input with this transformation method:
private class ShowNumbersTransformationMethod implements TransformationMethod {
public CharSequence getTransformation(final CharSequence charSequence, final View view) {
return new PassCharSequence(charSequence);
}
#Override
public void onFocusChanged(final View view, final CharSequence charSequence, final boolean b, final int i,
final Rect rect) {
//nothing to do here
}
private class PassCharSequence implements CharSequence {
private final CharSequence charSequence;
public PassCharSequence(final CharSequence charSequence) {
this.charSequence = charSequence;
}
#Override
public char charAt(final int index) {
return charSequence.charAt(index);
}
#Override
public int length() {
return charSequence.length();
}
#Override
public CharSequence subSequence(final int start, final int end) {
return new PassCharSequence(charSequence.subSequence(start, end));
}
}
}
and then set it to your edittext:
edittext.setTransformationMethod(new ShowNumbersTransformationMethod());
Now, as said before, this is not the happiest solution, but i assure you it works like a charm. It would be 10 times easier to create your own custom keyboard, but, i didnt have that option, since my client wanted the standard keyboard, god knows why...
Hope it helped!
The keyboard itself chooses what keys to layout. The best you can do is specify InputType.TYPE_CLASS_NUMBER, but the keyboard will still display whatever it thinks is appropriate to a numeric text field.

Android Login Alternatives

I'm implementing various things at the moment, but the one thing that boggles me is Android Login Mechanism. I'm not so sure which login mechanism to choose from in different applications (where all of them are accessing internet).
Let's say I have two apps:
A: This app basically should connect to the server and let users chat - we can see the online user list (no roster, everybody is friend with everybody), so it's a chatting application.
B. This app should authenticate to the server and let users post messages to their WALL or something, so when the other user comes online it will instantly display those messages to him.
I'm deliberately using "connect to the server" trying to be generic, since this is what I want to know. What type of authentication should I use, so that my server knows that the user is legitimate one:
1) Custom Registration + Login: I don't want to use that, since users don't want to register another username and there are a lot of alternatives available.
2) OpenID: I should use this when I only need authenticated users, without the need to access their private information on whatever site. I'm not too fond of this, because a browser needs to open for this to work.
3) OAuth: The same as OpenID, but I can also get access to private resources of the user. Here is the same problem, a browser needs to open exchanging the keys and tokens, so it doesn't make too good user experience.
4) AccountManager: This is a very good option, but I don't like it, since it's not a part of the application. I'm not even sure what should happen when the user hits the Login button, and AccountManager pops up. Should I choose the existing account alraedy listed in the AccountManager, what if I want to choose a different account, like Yahoo, etc - can AccountManager register it, login to it, and return the application - authenticated.
I would very much like to hear the existing implementations of all of the 4 alternatives that I can use. I know there are a lot of them out there and I don't want them listed here, I know them. The only problem is that I don't know which one of them to use, that will do the work the way I want. The following is a list of things I want:
1) In the application, when user clicks the Login button, something should open letting the user choose between the following alternatives: Google, Facebook, Yahoo, Twitter. The user should login with whatever account, which should be noted as authenticated.
2) That account should then be user as an access token to authenticate to my server - so my server only accepts the token and check that it's valid.
The whole point of this is that I don't have to implement login mechanism on my server, but users are still authenticated against my server, so we can exchange some data, etc.
package com.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText login_uname, login_pwd;
TextView invalid_error;
Button login_btn;
private boolean canExit;
TextView pword_showhide;
// string login_un,login_pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
login_uname = (EditText) findViewById(R.id.login_username);
login_pwd = (EditText) findViewById(R.id.login_password);
invalid_error = (TextView) findViewById(R.id.InvalidError);
login_btn = (Button) findViewById(R.id.login_btn);
// loginbutton.setEnabled(false);
invalid_error.setVisibility(View.GONE);
pword_showhide = (TextView) findViewById(R.id.pwd_showhide);
// pword_showhide.setText("show");
pword_showhide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (login_pwd.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
login_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
pword_showhide.setText("show");
} else {
login_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
pword_showhide.setText("hide");
}
login_pwd.setSelection(login_pwd.getText().length());
}
});
checkValidation();
login_uname.addTextChangedListener(mWatcher);
login_pwd.addTextChangedListener(mWatcher);
}
private void checkValidation() {
// TODO Auto-generated method stub
if ((TextUtils.isEmpty(login_uname.getText())) || (TextUtils.isEmpty(login_pwd.getText())))
login_btn.setEnabled(false);
else {
login_btn.setEnabled(true);
}
}
public void login(View view) {
if (login_uname.getText().toString().equals("a") && login_pwd.getText().toString().equals("a")) {
invalid_error.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_LONG).show();
login_uname.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_username, 0, 0, 0);
login_pwd.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_password, 0, 0, 0);
//correcct password
} else {
//wrong password
invalid_error.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Login fail", Toast.LENGTH_LONG).show();
login_uname.setCompoundDrawablesWithIntrinsicBounds( R.drawable.error_username, 0, 0, 0);
login_pwd.setCompoundDrawablesWithIntrinsicBounds( R.drawable.error_password,0, 0, 0);
}
}
TextWatcher mWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
checkValidation();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (canExit)
super.onBackPressed();
else {
canExit = true;
Toast.makeText(getApplicationContext(), "Press again to Exit", Toast.LENGTH_SHORT).show();
}
mHandler.sendEmptyMessageDelayed(1, 2000/*time interval to next press in milli second*/);// if not pressed within 2seconds then will be setted(canExit) as false
}
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
canExit = false;
break;
default:
break;
}
}
};
}
login_screen.xml
----------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Invalid Login Details"
android:id="#+id/InvalidError"
android:gravity="center"
android:background="#ff3a0f"
android:textColor="#FFF"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="50dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/login_lyt">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/login_username"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="User Name"
android:drawableLeft="#drawable/icon_username"
android:layout_marginTop="141dp" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="******"
android:drawableLeft="#drawable/icon_password"
android:ems="10"
android:id="#+id/login_password"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/pwd_showhide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/login_password"
android:layout_alignBottom="#+id/login_password"
android:layout_alignParentRight="true"
android:text="show" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"
android:background="#f0a422"
android:id="#+id/login_btn"
android:layout_below="#+id/login_password"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
package com.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText login_uname, login_pwd;
TextView invalid_error;
Button login_btn;
private boolean canExit;
TextView pword_showhide;
// string login_un,login_pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
login_uname = (EditText) findViewById(R.id.login_username);
login_pwd = (EditText) findViewById(R.id.login_password);
invalid_error = (TextView) findViewById(R.id.InvalidError);
login_btn = (Button) findViewById(R.id.login_btn);
// loginbutton.setEnabled(false);
invalid_error.setVisibility(View.GONE);
pword_showhide = (TextView) findViewById(R.id.pwd_showhide);
// pword_showhide.setText("show");
pword_showhide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (login_pwd.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
login_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
pword_showhide.setText("show");
} else {
login_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
pword_showhide.setText("hide");
}
login_pwd.setSelection(login_pwd.getText().length());
}
});
checkValidation();
login_uname.addTextChangedListener(mWatcher);
login_pwd.addTextChangedListener(mWatcher);
}
private void checkValidation() {
// TODO Auto-generated method stub
if ((TextUtils.isEmpty(login_uname.getText())) || (TextUtils.isEmpty(login_pwd.getText())))
login_btn.setEnabled(false);
else {
login_btn.setEnabled(true);
}
}
TextWatcher mWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
checkValidation();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (canExit)
super.onBackPressed();
else {
canExit = true;
Toast.makeText(getApplicationContext(), "Press again to Exit", Toast.LENGTH_SHORT).show();
}
mHandler.sendEmptyMessageDelayed(1, 2000/*time interval to next press in milli second*/);// if not pressed within 2seconds then will be setted(canExit) as false
}
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
canExit = false;
break;
default:
break;
}
}
};
}
login_screen.xml:
------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Invalid Login Details"
android:id="#+id/InvalidError"
android:gravity="center"
android:background="#ff3a0f"
android:textColor="#FFF"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="50dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/login_lyt">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/login_username"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="User Name"
android:drawableLeft="#drawable/icon_username"
android:layout_marginTop="141dp" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="******"
android:drawableLeft="#drawable/icon_password"
android:ems="10"
android:id="#+id/login_password"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/pwd_showhide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/login_password"
android:layout_alignBottom="#+id/login_password"
android:layout_alignParentRight="true"
android:text="show" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login"
android:background="#f0a422"
android:id="#+id/login_btn"
android:layout_below="#+id/login_password"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>

Selecting a RadioButton in a Radiogroup

I'm new to android and I was trying out an example program using the radiogroups. I have declared 2 radio buttons under the radiogroup. I wanted which radio button is selected in the
radiogroup. as wanted to use it in the if and the elseif condition of the Anonymous class new onClickListener.
I tried to declare an integer variable radio_selected and to get the return value of the radgrp.getCheckedRadioButtonId()
radio_selected = radgrp.getCheckedRadioButtonId(); and use the constant for comparision in the if and else if condition as,
if( radio_selected == R.id.rdb1 && (edit1.getText().toString().equals("admin")) && (edit2.getText().toString().equals("admin")))
I tried to print the value of radio_selected . Its printing me -1 which means empty selection. But radgrp.getCheckedRadioButtonId(); is returning a integer value.
However the above program compiles and works fine but i wanted to know why i could not use radio_selected constant to do the comparision?
.java file
package android.button;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class Android_eg2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final int radio_selected;
final EditText edit1 = (EditText)findViewById(R.id.txt1);
final EditText edit2 = (EditText)findViewById(R.id.txt2);
edit2.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(edit2.getText().toString().length()>5){
Toast.makeText(getApplicationContext(), "EXCEEDED the MAX LIMIT", Toast.LENGTH_LONG).show();
}
return false;
}
});
final RadioGroup radgrp = (RadioGroup)findViewById(R.id.rad);
//radio_selected = radgrp.getCheckedRadioButtonId();
Button bt = (Button)findViewById(R.id.button);
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//System.out. println(radgrp.getCheckedRadioButtonId());
//System.out.println(radio_selected);
// TODO Auto-generated method stub
if(R.id.button == v.getId()){
if( radgrp.getCheckedRadioButtonId() == R.id.rdb1 && (edit1.getText().toString().equals("admin")) && (edit2.getText().toString().equals("admin"))){
Toast.makeText(getApplicationContext(),"LOGIN SUCCESS FOR ADMIN",Toast.LENGTH_LONG).show();
Log.v("TAG","In admin");
}
else if(radgrp.getCheckedRadioButtonId() == R.id.rdb2 && (edit1.getText().toString().equalsIgnoreCase("user")) && (edit2.getText().toString().equalsIgnoreCase("user"))){
Toast.makeText(getApplicationContext(),"LOGIN SUCCESS FOR USER",Toast.LENGTH_LONG).show();
Log.v("TAG","In user");
}
else{
Toast.makeText(getApplicationContext(),"INVALID ENTRY",Toast.LENGTH_LONG).show();
Log.v("TAG","Invalid");
}
}
}
});
radgrp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.rdb1:
//Toast.makeText(getApplicationContext(),"ADMIN",Toast.LENGTH_LONG).show();
case R.id.rdb2:
//Toast.makeText(getApplicationContext(),"USER",Toast.LENGTH_LONG).show();
}
}
});
}
}
main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to wipro"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioGroup
android:id="#+id/rad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<RadioButton
android:id="#+id/rdb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Admin"
>
</RadioButton>
<RadioButton
android:id="#+id/rdb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "User"
>
</RadioButton>
</RadioGroup>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/lbl1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="USER NAME"
android:textSize="6pt"
android:textColor = "#00aa00"
>
</TextView>
<EditText
android:id="#+id/txt1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text=""
android:textSize="6pt"
android:textColor = "#aa0000"
>
</EditText>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/lbl2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="PASSWORD"
android:textSize="6pt"
android:textColor="#00aa00"
android:layout_weight="1"
>
</TextView>
<EditText
android:id="#+id/txt2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text=""
android:textSize="6pt"
android:textColor = "#aa0000"
android:password = "true"
>
</EditText>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUBMIT"
>
</Button>
</LinearLayout>
</LinearLayout>
R.java file
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package android.button;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int button=0x7f050007;
public static final int lbl1=0x7f050003;
public static final int lbl2=0x7f050005;
public static final int rad=0x7f050000;
public static final int rdb1=0x7f050001;
public static final int rdb2=0x7f050002;
public static final int txt1=0x7f050004;
public static final int txt2=0x7f050006;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}
boolean rad1,rad2=false;
radio1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(radio1.isChecked())
{
rad1=true;
}
}
});
radio2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
ifradio2.isChecked())
{
rad2=true;
}
}
});
Hey Angus I think that you almost got it right. The reason your radio_selected variable is printing that value is because you are trying to obtain which radio button is selected while the activity is being created and there are no selected radio buttons, so its value will be -1.
Apart from this I would recommend you to implement OnCheckedChangeListener in your activity class, which would allow you to override the onCheckedChanged method to capture the selection of a radio button. In your case you declared your radio_selected as a final variable, which is an error! Final means that once that variable is defined its value cannot be changed so even if it worked, it would work for the first time and not again. So, with these pieces of advice your activity could look like this:
//all of the imports
public class TestActivity extends Activity implements OnCheckedChangeListener{
private int radio_selected;//now radio_selected is a class variable
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText edit1 = (EditText)findViewById(R.id.txt1);
final EditText edit2 = (EditText)findViewById(R.id.txt2);
edit2.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event)
{
// TODO Auto-generated method stub
if(edit2.getText().toString().length()>5)
{
Toast.makeText(getApplicationContext(), "EXCEEDED the MAX LIMIT", Toast.LENGTH_LONG).show();
}
return false;
}
});
final RadioGroup radgrp = (RadioGroup)findViewById(R.id.rad);
Button bt = (Button)findViewById(R.id.button);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
System.out. println(radgrp.getCheckedRadioButtonId());
System.out.println(radio_selected);
// TODO Auto-generated method stub
if(R.id.button == v.getId())
{
if( radgrp.getCheckedRadioButtonId() == R.id.rdb1 && (edit1.getText().toString().equals("admin")) && (edit2.getText().toString().equals("admin")))
{
Toast.makeText(getApplicationContext(),"LOGIN SUCCESS FOR ADMIN",Toast.LENGTH_LONG).show();
Log.v("TAG","In admin");
}
else if(radgrp.getCheckedRadioButtonId() == R.id.rdb2 && (edit1.getText().toString().equalsIgnoreCase("user")) && (edit2.getText().toString().equalsIgnoreCase("user")))
{
Toast.makeText(getApplicationContext(),"LOGIN SUCCESS FOR USER",Toast.LENGTH_LONG).show();
Log.v("TAG","In user");
}
else{
Toast.makeText(getApplicationContext(),"INVALID ENTRY",Toast.LENGTH_LONG).show();
Log.v("TAG","Invalid");
}
}
}
});
radgrp.setOnCheckedChangeListener(this); //you set this activity as the listener for the events on the radio group...
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.rdb1:
radio_selected = R.id.rdb1;
Toast.makeText(getApplicationContext(),"ADMIN",Toast.LENGTH_LONG).show();
case R.id.rdb2:
radio_selected = R.id.rdb2;
Toast.makeText(getApplicationContext(),"USER",Toast.LENGTH_LONG).show();
}
}
}
Notice that I set the value of radio_selected whenever a radio button is selected, this way it will be updated once the submit button is pressed.
I hope I have been clear enough, code can still be improved but that's for another answer ;)
Cheers!
RadioGroup radioGroup ;
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
Toast.makeText(getApplicationContext(),"RadioButton1selected",Toast.LENGTH_LONG.show();
case R.id.radio2:
Toast.makeText(getApplicationContext(),"RadioButton2selected",Toast.LENGTH_LONG).show();}

Categories

Resources