我开始时使用一个简单的应用程序,当一个按钮改变文本我想改变它从说'hello world'到'hello brody'当我按下这里的按钮是我得到的
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.helloworld.app.MainActivity">
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="145dp"
android:textSize="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
我该怎么做才能改变文字?
答案 0 :(得分:3)
试试这样。它会帮助你
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
yourTextViewObject.setText("Hello World");
} else {
yourTextViewObject.setText("Hello Brody");
}
}
});
答案 1 :(得分:1)
很简单的例子:
public class MainActivity extends Activity
{
TextView textView;
ToggleButton toggleButton;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton btn, boolean checked)
{
textView.setText(checked ? "hello brody" : "hello world");
}
}
);
}
}
要与您提供的布局xml保持一致,您需要将以下行添加到TextView
标记:
android:id="@+id/textView"
答案 2 :(得分:0)
嗨,看看这里的给定代码
ToggleButton toggleButton= (ToggleButton) findViewById(R.id.togglebutton);
toggleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (toggleButton.isChecked()) {
//do accordingly
} else {
//do accordingly
}
}
});