我正在尝试将按钮连接到文本,基本上每当有人按下按钮时文本都会更改。我写了5个over-riding方法续。在侦听器方法中命名为onClick(View v)。但是当我构建我的应用程序并在我的设备上打开它时,只打印了最后一条消息,我知道这是因为最后的overRiding方法会将其他消息静音,但是如何在每次点击按钮时逐个打印所有消息。
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
Main-Class: com.my.package.fooClass
答案 0 :(得分:0)
您可以在变量中维护当前状态,并根据状态设置正确的文本。像,
int currentState = 0;
TextView Text;
public void onCreate(Bundle savedInstanceState) {
Button new_button = (Button) findViewById(R.id.Button);
Text = (TextView) findViewById(R.id.Text);
//now we gotta set up the event listener
new_button.setOnClickListener(
//here we will put call back method,
//after someone click the button
//this methods's body get's executed
//this is interface
new Button.OnClickListener(){
public void onClick(View v){
if (currentState == 0) {
Text.setText("YOU PRESSED IT!");
currentState++;
} else if (currentState == 1) {
Text.setText("Please don't press it again :)");
currentState++;
}
... and so on ...
}
}
);
答案 1 :(得分:-1)
你走了!不要忘记在下面的文件中编辑YOUR_PROJECT
。
您的Java文件:
package YOUR_PROJECT;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import static YOUR_PROJECT.R.*;
public class Test extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_test);
Button new_button = (Button) findViewById(R.id.Button);
new_button.setOnClickListener(new View.OnClickListener() {
int i = 0;
TextView Text = (TextView) findViewById(R.id.Text);
@Override
public void onClick(View arg0) {
if (i == 0) {
Text.setText("YOU PRESSED IT!");
i++;
} else {
if (i == 1) {
Text.setText("Please don't press it again :)");
i++;
} else {
if (i == 2) {
Text.setText("Please Stop It!");
i++;
} else {
if (i == 3) {
Text.setText("Stop Pressssssing It");
i++;
} else {
if (i == 4) {
Text.setText("You Pressed it again! >:{");
} else
i = 0;
}
}
}
}
}
});
}
}
您的XML:
<?xml version="1.0" encoding="utf-8"?>
<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="YOUR_PROJECT.Test">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/Button"
android:layout_marginTop="101dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:layout_below="@+id/Button"
android:layout_alignEnd="@+id/Button"
android:layout_marginTop="125dp" />
</RelativeLayout>