需要仅包含数字的软键盘吗?

10
你好,我需要一个只有数字值和回车键的软键盘,数字从09。不应该显示除此之外的任何其他字符,如. , ( )等等...

enter image description here

我尝试了几个选项如此处所建议,但似乎没有任何一种适合我。

  1. setRawInputType(Configuration.KEYBOARD_QWERTY)
  2. setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED)
  3. setRawInputType(InputType.TYPE_CLASS_NUMBER)
  4. setRawInputType(InputType.TYPE_CLASS_PHONE)

我总是在键盘上看到额外的字符,例如:

enter image description here

setRawInputType(Configuration.KEYBOARD_12KEY)会显示一个类似这样的键盘:

enter image description here

我很乐意为您提供帮助。以下是需要翻译的内容:

非常感谢任何帮助。提前致谢。

注意:

  • android:minSdkVersion="14":ICS4.0
  • android:targetSdkVersion="17":JB 4.2

setRawInputType(Configuration.KEYBOARD_12KEY)是什么意思? - yarian
发布已更新,附带截图。 - Akh
7个回答

4

我曾经遇到过同样的问题,并且发现没有类似的android键盘可用,唯一的方法就是实现自己的键盘。因此,我想分享我的实现方法,希望能为您节省宝贵的时间:

  1. 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>
    

enter image description here

  1. 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. 当按下EditText时,弹出键盘的效果是通过创建一个空的RelativeLayout作为键盘的容器来实现的:

<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>

当用户点击EditText时,我们将Fragment添加到容器中,当用户按下完成按钮时,我们隐藏它。键盘Fragment使用onKeyBoardEvent接口与Activity进行通信。 注意:托管Activity必须实现此接口,否则会抛出ClassCastException异常。

非常重要:我没有处理方向变化,如果你在键盘打开时切换到横屏模式,应用程序将崩溃,因此要么禁用横屏模式,要么处理方向变化以避免key_board_fragment上的NullPointerException。

这是实现keyBoard功能的Activity:

     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();
}
       }

最后一件事:

为了禁用Android标准键盘的弹出,我创建了一个CustomEditText类,在onCheckIsTextEditor()方法中简单地返回false。以下是CustomEditText类:

 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;
}
    }

希望我能帮到你... 如果你有改进建议,我很愿意听取。 加尔。

3
这适合写成一篇博客文章。 - Nirmal

4

对于标准键盘,您只能建议输入类型。键盘仍然可以显示或不显示它想要的任何键。如果您必须拥有某些特定的键,而且只有这些键,您需要创建一个自定义软键盘。如果它仅用于您的应用程序,特别是如果它仅用于一个活动,则我实际上不会实现标准键盘,而只是使用视图/按钮执行相应的操作。


1
这个解决方案使用numberPassword,通过覆盖EditText的默认转换方法来显示字符而不是点。
<EditText
    android:id="@+id/userid"
    android:inputType="numberPassword"
    android:maxLength="6"
/>

添加到OnCreate中。
// Numeric 6 character user id
EditText input = findViewById(R.id.userid);

// Process input and show characters instead of dots
input.setTransformationMethod(SingleLineTransformationMethod.getInstance());

Numeric soft keyboard Image


1
除此之外,在EditText上设置。这将在您开始输入时打开数字键盘,但它将包括与数字相关的所有额外字符。您需要实现自己的键盘,以仅保留数字值。

我尝试了inputType="phone",就像你提到的那样,它仍然显示了那些额外的字符。我认为自定义键盘是正确的方法。谢谢。 - Akh

1

默认情况下,基于您的设备,键盘在数字键盘中也显示特殊字符。通过为文本字段指定键盘类型,您可以实现预期结果,例如:

 InputFieldName.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

如果您只需要包含特殊字符的数字,则可以使用InputType.TYPE_CLASS_NUMBER 或者,如果您还需要排除那些特殊字符,则使用InputType.TYPE_NUMBER_VARIATION_PASSWORD

0

我曾经遇到过你现在面临的同样问题,不过我找到了一个解决方案。也许它并不优雅,也不简单,但确实非常有效...

首先,目前(至少到4.3版本为止)唯一能与该键盘兼容的InputType是“numberPassword”,但这会将你的输入隐藏成点。因此,我使用了这种输入方式,并结合了以下转换方法:

    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));
        }
    }
}

然后将其设置为您的EditText:

edittext.setTransformationMethod(new ShowNumbersTransformationMethod());

现在,正如之前所说,这不是最好的解决方案,但我向您保证它能够完美运行。创建自己的自定义键盘会更容易十倍,但是,由于我的客户想要标准键盘,我没有这个选项,天知道为什么...

希望对您有所帮助!


设置numberPassword将使您失去此组件的自定义字体。 - Cassio Landim

0

键盘本身选择什么键来布局。你能做的最好的事情就是指定InputType.TYPE_CLASS_NUMBER,但是键盘仍然会显示它认为适合数字文本字段的任何内容。


谢谢。在程序中,我可以提及编辑文本中可以预期的输入类型吗? - Akh
所有设备上的锁屏似乎都只有数字键盘。不知道这些是系统键盘还是自定义键盘? - Akh
2
它们是定制的。你总是可以编写自己的自定义键盘,但这并不值得花费太多时间。对于数字键盘,你甚至最好不要将其制作成键盘,而是像一个巨大的计算器应用程序一样运行。我认为这就是他们所做的——在键盘布局中有9个按钮,并在按钮的onClick中手动插入文本。 - Gabe Sechan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接