Example on ToggleButton

后端 未结 7 1299
悲哀的现实
悲哀的现实 2021-01-12 07:08

I am developing an application using a toggle button, I entered 1 or 0 in EditText. When button is clicked, the toggle button has to change if I enter 1 the tog

7条回答
  •  悲哀的现实
    2021-01-12 07:31

    Move this

     btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
         editString = ed.getText().toString();
    

    inside onClick

    Also you change the state of the toogle button whether its 0 or 1

    http://developer.android.com/guide/topics/ui/controls/togglebutton.html

    Example:

    
    
        

    MainActivity.java

    public class MainActivity extends Activity implements OnClickListener {
    
        EditText ed;
        Switch sb;
        ToggleButton tb;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ed = (EditText) findViewById(R.id.editText1);
            Button b = (Button) findViewById(R.id.button1);
            sb = (Switch)findViewById(R.id.switch1);
            tb = (ToggleButton)findViewById(R.id.togglebutton);
            b.setOnClickListener(this);
        }
    
    
        @Override
        public void onClick(View v) {
            String s = ed.getText().toString();
             if(s.equals("1")){
    
                 tb.setText("TOGGLE ON");
                 tb.setActivated(true);
                 sb.setChecked(true);
    
             }
             else if(s.equals("0")){
    
                 tb.setText("TOGGLE OFF");
                 tb.setActivated(false);
                 sb.setChecked(false);
    
        }
    
        }
         }
    

    Snaps

    enter image description here

    enter image description here

提交回复
热议问题