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:
<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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:text="Button" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:ems="10" >
<requestFocus />
</EditText>
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="51dp"
android:text="Switch" />
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/switch1"
android:layout_marginTop="58dp"
android:onClick="onToggleClicked"
android:textOff="Vibrate off"
android:textOn="Vibrate on" />
</RelativeLayout>
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