开发者

Change EditText by Button

开发者 https://www.devze.com 2023-03-13 15:07 出处:网络
I am having EditText and using the numbers inside the EditText for my variables. I am also having two buttons, one to increase the number in EditText by one and another to decrease it by one.

I am having EditText and using the numbers inside the EditText for my variables.

I am also having two buttons, one to increase the number in EditText by one and another to decrease it by one.

Can somebody tell me the code to make thi开发者_开发问答s possible?


Use the following line in the xml of EditText for setting the input type as number :

<EditText 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:inputType="number" 
            android:text="200"
            android:id="@+id/editText1" 
            android:layout_alignParentLeft="true">
        </EditText> 

And in source file use the following code to decrease the number by 1:

final EditText ed=(EditText)findViewById(R.id.editText1);

        Button b1=(Button)findViewById(R.id.button01);

        b1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub

                int a=Integer.parseInt(ed.getText().toString());

                int b=a-1;

                ed.setText(new Integer(b).toString());
            }
        });

Similarly add one more button in the xml to increase the number by one.


You need to create a on click listener for each button, doing something like:

 final Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                EditText editText = (EditText)findViewById(R.id.edit_text);
                int newVal = ... //retrieve the previous val and increment it (or decrement it)
                editText.setText(newVal, TextView.BufferType.EDITABLE);
             }
         });


Simply you have to use the click event of both the buttons, on increase button get the text in edittextbox and increment it and set it in the edittextbox, same way do for decrement button also and decrement the value.


button.setOnClickListener(new OnCLickListener(){
    @Override
    public void onClick(View arg0) {
    if(arg0.equals(button1))
    {
        String s = editText.getText().toString();
        Integer i = Integer.parseInt(s);
        i=++i;
        s = s.valueOf(i);
        editText.setText(s);
    }
    if(arg0.equals(button2))
    {
//decrement
    }
    }
})
0

精彩评论

暂无评论...
验证码 换一张
取 消