调用Toast类的以下方法,可创建Toast:
public static Toast makeText(Context context, int resId, int duration)
该方法的Context参数通常是Activity的一个实例(Activity本身就是Context的子类).第二个参数是toast要显示字符串消息的资源ID.Toast类必须借助COntext才能找到并使用字符串资源ID.第三个参数通常是两个Toast常量中的一个,用来指定toast消息的停留时间.
创建toast后,可调用Toast.show()方法在屏幕上显示toast消息.
在QuizActivity代码里,分别调用makeText(...)方法,如代码QuizActivity所示.在添加makeText(...)时,可利用Android Studio的代码自动补全功能,让代码输入更轻松.
string.xml:
<resources>
<string name="app_name">GeoQuiz</string>
<string name="question_text">Canberra is the capital of Australis.</string>
<string name="true_button">True</string>
<string name="false_button">False</string>
<string name="correct_toast">Correct!</string>
<string name="incorrect_toast">Incorrect!</string>
</resources>
activity_quiz:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="www.lvluohudong.com.geoquiz.QuizActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="@string/question_text" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/true_button" />
<Button
android:id="@+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/false_button" />
</LinearLayout>
</LinearLayout>
QuizActivity:
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseBuuton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//引用组件
mTrueButton = findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.correct_toast,
Toast.LENGTH_LONG).show();
}
});
mFalseBuuton = findViewById(R.id.false_button);
mFalseBuuton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.incorrect_toast,
Toast.LENGTH_LONG).show();
}
});
}
}
在makeText(...)里,传入QuizActivity实例作为Context的参数值.注意此处输入的参数是QuizActivity.this,不要想当然的直接传入this.因为匿名内部类的使用,这里的this只的是监听器View.OnClickListener.