任何人都可以帮我编写一个切换按钮的代码(1就够了),功能简单(一个文本或消息,例如:on,off会在点击切换按钮时弹出)?
尽可能简单,因为我刚开始这几天,我的应用程序一直在崩溃。
或许有人可以发现我的错误?
package com.example.ledfinal;
import com.example.ledfinal.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;
public class MainActivityled extends Activity {
ToggleButton button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activityled);
button = (ToggleButton) findViewById(R.id.toggleButton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (button.isChecked()){
System.out.println("On");
}
else{
System.out.println("Off");
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activityled, menu);
return true;
}
}
答案 0 :(得分:0)
这是关于简单toggleButton
的代码xml:
<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="#000000"
>
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn" />
</LinearLayout>
values / string.xml添加此行
<string name="btn">see option</string>
MainActivity:
public class MainActivity extends Activity {
ToggleButton toggleButton;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("toggleButton1 : ").append(toggleButton.getText());
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_SHORT).show();
}
});
}
}