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.
Related
I'm currently working on an application and I have and unwanted behavior on my custom EditText Dialog. Here's the XML code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/editText_dialog"
android:layout_width="fill_parent"
android:inputType="textCapSentences"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/close_dialog"
android:id="#+id/cancel_dialog"
android:textSize="20sp"
android:layout_margin="20dp"
android:layout_gravity="right"
android:layout_toLeftOf="#+id/valid_dialog" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/validate_dialog"
android:id="#+id/valid_dialog"
android:textSize="20sp"
android:layout_margin="20dp"
android:layout_gravity="right"
android:textColor="#android:color/holo_blue_light"
android:layout_alignParentRight="true" />
</RelativeLayout>S7
</LinearLayout>
And here is the class for the TextEditDialog
package com.fitme.staffbooker;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.NumberPicker;
public class EditTextDialog extends Dialog {
private EditText editText;
public boolean dismissed = false;
public EditTextDialog(Context context, String title) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
setTitle(title);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);
editText = (EditText) findViewById(R.id.editText_dialog);
findViewById(R.id.valid_dialog).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismissed = true;
dismiss();
}
});
findViewById(R.id.cancel_dialog).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel();
}
});
}
public void setHint(String str) {
editText.setHint(str);
}
public void setText(String str) {
editText.setText(str);
}
public void setInputType(int type) {
editText.setInputType(type);
}
public String getValue() {
return editText.getText().toString();
}
}
Here's the output i'm having on my Galaxy S7 Edge :
But when I'm running my app on a Galaxy SIII Emulator it seems broken :
It seems that this only happens on 4.3 and below. I have no idea what is happening.
In my TopRated.java file, I have an image view which changes when the seekbar is used. It also changes when the next and previous buttons are used. however, i want both buttons and the seeker to be in sync, that is, when the next button is pressed, i want it to also move the seeker up by one, and when the previous button is pressed, i want it to also move the seeker down by one.
please help
This is my TopRated.java file
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
public class TopRated extends Activity {
SeekBar imgseekbar;
ImageView iconimageview;
Button prevbutton;
Button nextbutton;
int progress=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.toprated);
iconimageview=(ImageView)findViewById(R.id.imageView);
imgseekbar=(SeekBar)findViewById(R.id.seekBar);
prevbutton=(Button)findViewById(R.id.button8);
nextbutton=(Button)findViewById(R.id.button9);
iconimageview.setImageResource(R.drawable.diablo);
imgseekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
updateImageResource(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
prevbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress--;
updateImageResource(progress);
}
});
nextbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress++;
updateImageResource(progress);
}
});
}
private void updateImageResource(int progress) {
if (progress==2) {
iconimageview.setImageResource(R.drawable.eye);
}else if (progress==3) {
iconimageview.setImageResource(R.drawable.facebook);
}else if (progress==4) {
iconimageview.setImageResource(R.drawable.google);
}else if (progress==5) {
iconimageview.setImageResource(R.drawable.house);
}else if (progress==6) {
iconimageview.setImageResource(R.drawable.mail);
}else if (progress==7) {
iconimageview.setImageResource(R.drawable.pen);
}else if (progress==8) {
iconimageview.setImageResource(R.drawable.photos);
}else if (progress==9) {
iconimageview.setImageResource(R.drawable.skype);
}else if (progress==10)
iconimageview.setImageResource(R.drawable.twitter);
}
}
This is my toprated.xml file
<?xml version="1.0" encoding="utf-8"?>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBar"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:max="10"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_below="#+id/seekBar"
android:layout_centerHorizontal="true"
android:minHeight="50dp"
android:minWidth="50dp"
android:background="#drawable/icon_animation"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Prev"
android:id="#+id/button8"
android:layout_alignBottom="#+id/imageView"
android:layout_toStartOf="#+id/imageView"
android:layout_marginRight="5dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:id="#+id/button9"
android:layout_alignBottom="#+id/imageView"
android:layout_toEndOf="#+id/button8"
android:layout_marginLeft="50dp" />
I also have another xml which holds all my images, icon_animation.xml
please help!
any help would be appreciated.
use below line to update seek bar
seekbar.setProgress(int)
i've created an android application which displays a number picker, it all works fine...but the problem is with the design....when i run the application in gingerbread the number picker looks fine good....but when i run the same stuff in ice-cream sandwich and jelly bean the number picker design is been altered just like as shown below.
can anyone please tell me how to retain the default number-picker design that is in gingerbread in jelly bean
when runs in ice-cream sandwich and jelly bean
when runs in ginger-bread
i'm using a custom dialog box within which the number picker is placed, the code is as given below
import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.NumberPicker;
public class QuantityChangeDialog extends Dialog implements android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button save, cancel;
NumberPicker np;
public QuantityChangeDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
setContentView(R.layout.selecteditem_dialog);
save = (Button) findViewById(R.id.btn_save);
cancel = (Button) findViewById(R.id.btn_cancel);
save.setOnClickListener(this);
cancel.setOnClickListener(this);
np = (NumberPicker) findViewById(R.id.qntypicker);
np.setMaxValue(120);
np.setMinValue(1);
np.setValue(3);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
c.finish();
break;
case R.id.btn_cancel:
dismiss();
break;
default:
break;
}
dismiss();
}
}
Quoting from docs
If the current theme is derived from Theme the widget presents the current value as an editable input field with an increment button above and a decrement button below. Long pressing the buttons allows for a quick change of the current value. Tapping on the input field allows to type in a desired value.
You need to set your theme that is derieved from Theme like fro example Theme.NoTitleBar.Fullscreen
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" />
<Button
android:id="#+id/button11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Open" />
</RelativeLayout>
dialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:theme = "#style/cust_dialog"
android:layout_height="fill_parent" >
<NumberPicker
android:id="#+id/numberPicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/numberPicker1"
android:layout_marginLeft="20dp"
android:layout_marginTop="98dp"
android:layout_toRightOf="#+id/numberPicker1"
android:text="Cancel" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_marginRight="16dp"
android:layout_toLeftOf="#+id/numberPicker1"
android:text="Set" />
</RelativeLayout>
Then to display custom dialog
public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener
{
private TextView tv;
static Dialog d ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
tv.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
tv.setTextColor(Color.RED);
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
// set to normal color
tv.setTextColor(0);
}
return true;
}
});
Button b = (Button) findViewById(R.id.button11);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
show();
}
});
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
Log.i("value is",""+newVal);
}
public void show()
{
final Dialog d=new Dialog(this,R.style.cust_dialog);
d.setTitle("NumberPicker");
d.setContentView(R.layout.dialog);
Button b1 = (Button) d.findViewById(R.id.button1);
Button b2 = (Button) d.findViewById(R.id.button2);
final NumberPicker np = (NumberPicker) d.findViewById(R.id.numberPicker1);
np.setMaxValue(100);
np.setMinValue(0);
np.setWrapSelectorWheel(false);
np.setOnValueChangedListener(this);
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
tv.setText(String.valueOf(np.getValue()));
d.dismiss();
}
});
b2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
}
Styles.xml
</style>
<style name="cust_dialog" parent="#android:style/Theme.NoTitleBar.Fullscreen">
</style>
Snap Shot
You can just add this attribute into your NumberPicker
android:theme="#android:style/Theme.Dialog"
E.g.
<NumberPicker android:theme="#android:style/Theme.Dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This will limit the impact to just the number picker widget, not the entire activity page.
I am trying to read stuff from a SeekBar in Android that's within a DialogFragment. It keep crashing. The SeekBar alone comes up no problem, but whenever I try to override functions so I can use the SeekBar for something it keeps crashing. I've tried copying basically what I've seen other people post as working code (though not within a DialogFragment) but it doesn't work. Can someone tell me what's wrong here?
numColumnsControl = (SeekBar) getActivity().findViewById(R.id.seekBar1);
numColumnsControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
//#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean fromTouch)
{
((TextView) (getActivity().findViewById(R.id.textView2))).setText(String.valueOf(progress));
}
//#Override
public void onStartTrackingTouch(SeekBar arg0)
{
// TODO Auto-generated method stub
}
//#Override
public void onStopTrackingTouch(SeekBar arg0)
{
// TODO Auto-generated method stub
}
});`
It keeps crashing whenever I perform the action to open the DialogFragment. When I comment out the entire section it is fine. The problem is somehow overriding those functions, even when they're empty. When this entire section is commented the View comes up with SeekBars and TextViews.
I don't think this is important but here's the XML for the DialogFragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Settings"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/seekBar1"
android:layout_marginTop="20dp"
android:text="NumShifts"
android:textAppearance="?android:attr/textAppearanceSmall" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:gravity="center"
android:layout_gravity="center"
android:max="15"
android:progress="6"
android:secondaryProgress="0"/>
<SeekBar
android:id="#+id/SeekBar01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:gravity="center"
android:layout_gravity="center"
android:max="9"
android:progress="3"
android:secondaryProgress="0"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/titleText"
android:layout_below="#+id/titleText"
android:layout_marginTop="18dp"
android:text="NumColumns"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
Here is the whole code from the class:
package com.example.[I have to hide this name];
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SettingsDialogueFragment extends DialogFragment
{
private int numColums;
private int numShifts;
private Context ctx;
private SeekBar numColumnsControl = null;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
ctx = getActivity();
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater= getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.settings_menu, null))
.setPositiveButton("DONE", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
//done
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
LinearLayout settings = new LinearLayout(ctx);
numColumnsControl = (SeekBar) getActivity().findViewById(R.id.seekBar1);
Activity myActivity = getActivity();
if(myActivity == null)
{
Log.e("bill", "bill");
}
if(numColumnsControl == null)
{
Log.e("smith", "smith");
}
numColumnsControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
//#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean fromTouch)
{
((TextView) (getActivity().findViewById(R.id.textView2))).setText(String.valueOf(progress));
Log.e("asd", "asd");
}
//#Override
public void onStartTrackingTouch(SeekBar arg0)
{
Log.e("asdf", "asdf");
// TODO Auto-generated method stub
}
//#Override
public void onStopTrackingTouch(SeekBar arg0)
{
Log.e("asdfg", "asdfg");
// TODO Auto-generated method stub
}
});
return builder.create();
}
}
Based on your comment
'The error is a NullPointerException, which occurs on line 51 which is
the 2nd line in the fragment I gave you
("numColumnsControl.setOnSeekBarChangeListener(new
OnSeekBarChangeListener() ")'
Check if findViewById(R.id.Seekbar1) doesn't returns null. If it does, Make sure your dialog layout is inflated before requesting any view elements from the layout.
It is also possible something is going wrong with the R references (try project -> clean in eclipse) .
Edit I'm not sure if it works, but try to overide onViewCreated() and place your findViewById and setOnSeekBarChangeListener code here.
Edit in some way onViewCreated() is not called (Android DialogFragment onViewCreated not called). This makes the solution a little more difficult. You need to inflate the view first and perform an findViewById on the inflated view.
View menuView = inflater.inflate(R.layout.settings_menu);
numColumnsControl = (SeekBar) menuView.findViewById(R.id.seekBar1, null);
numColumnsControl.setOnSeekBarChangeListener ...
builder.setView(menuView);
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;
}
}