我想制作一个可点击的按钮,当我点击它时,它会显示一条短信。我写了以下代码:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
tools:context="com.example.android.quiztime.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<ImageButton
android:src="@drawable/football"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:clickable="true"
android:id="@+id/football"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/texty"/>
</LinearLayout>
Java文件:
package com.example.android.quiztime;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton imageButton = (ImageButton) findViewById(R.id.football);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final TextView textView = (TextView) findViewById(R.id.texty);
textView.setText("Click success");
}
});
}
}
我还尝试将ImageButton更改为ImageView并尝试使用setOnClickListener。但徒劳无功。请告诉我我哪里出错了。
答案 0 :(得分:0)
您可以将android:onClick
添加到xml文件
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
tools:context="com.example.android.quiztime.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<ImageButton
android:src="@drawable/football"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:clickable="true"
android:onClick="pritnText"
android:id="@+id/football"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/texty"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton = (ImageButton) findViewById(R.id.football);
}
public void printText(View v) {
Log.d("DEBUG","WORKS");
}
}