【问题标题】:Android user input, using a custom keypadAndroid 用户输入,使用自定义键盘
【发布时间】:2012-02-21 22:56:08
【问题描述】:

对于初学者,任何帮助将不胜感激!我创建了一个数字小键盘,每次选择其中一个按钮时,我都需要将数值传递给 EditText。我遇到了一个问题,即每次按下不同的按钮时,EditText 都会被 setText 覆盖。我真的需要连接每个值,我不太确定如何做到这一点。可以按任意顺序按下一到九个按钮中的任何一个。

这里是一些代码。我只是想让这些键先工作。

    View hash = findViewById(R.id.keypad_hash);
    hash.setOnClickListener(this);
    View key1 = findViewById(R.id.keypad_1);
    key1.setOnClickListener(this);
    View key2 = findViewById(R.id.keypad_2);
    key2.setOnClickListener(this);

}




@Override
public void onClick(View v){
switch(v.getId()){
case R.id.keypad_hash:
    questions();
    break;

case R.id.keypad_1:

    final EditText number_edit_text1 = (EditText) this.findViewById(R.id.Edit);
      number_edit_text1.setText(String.valueOf("1"));




      break;


case R.id.keypad_2:

    final EditText number_edit_text2 = (EditText) this.findViewById(R.id.Edit);
      number_edit_text2.setText(String.valueOf("2"));
    break;

}   
}

然后是布局中的edittext

<EditText  
android:id="@+id/Edit"  
android:layout_height="wrap_content"    
android:inputType="number"  
android:layout_width="fill_parent"
android:numeric="integer">  
</EditText> 

【问题讨论】:

    标签: android android-layout android-edittext android-keypad


    【解决方案1】:

    试试:

    number_edit_text2.append(String.valueOf("2"));
    

    如果由于某种原因不起作用:

    number_edit_text2.setText(number_edit_text2.getText().toString()+String.valueOf("2"));
    

    另外,顺便说一句,您可以让自己的过程更轻松。

    在你的 xml 中,你应该这样做:

    android:tag="0"
    

    并将 0 替换为每个按钮所需的任何数字。

    在你的类中,你应该声明EditText editText;,然后在onCreate,你应该声明editText = (EditText)findViewById(R.id.Edit);

    然后在onClick,就这样:

    editText.append(String.valueOf(v.getTag()));
    

    这应该会简化您的代码,使其更易于管理,并使用更少的资源,因为您不必反复重新创建 EditText

    【讨论】:

    • 您好,感谢您的快速回复。我实施了你的建议,我已经开始工作了。非常感谢您的详细回答。感激不尽。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2021-06-21
    • 2022-01-24
    • 2017-10-25
    • 2016-01-09
    相关资源
    最近更新 更多