Android开发初体验
1.创建一个新项目
项目名称改为自己的网卡地址加学号和项目名
2.给项目添加一个子类
按照下图方式添加一个子类
3.子类命名
命名activity子类为QuizActivity,如下图所示
4.用户界面设置
打开activity_quiz.xml文件,将原来的代码修改为以下代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
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>![在这里插入图片描述](https://img-blog.csdnimg.cn/202011302129090.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xvdmVseVhH,size_16,color_FFFFFF,t_70)
5.创建字符串资源
打开strings.xml文件,将原有代码添加以下代码
<string name="question_text">Canberra is the capital of Australia.</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>
6.预览布局
应用的界面布局已经完成
7.从布局XML到视图对象
打开QuizActivity类文件将其代码修改为
package com.example.a5c_ba_ef_2a_aa_c5462;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.example.a5c_ba_ef_2a_aa_c5462.R;
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton=(Button) 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_SHORT).show();
// Does mothing yet, but soon!
}
});
mFalseButton=(Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Toast.makeText(QuizActivity.this,
R.string.incorrect_toast,
Toast.LENGTH_SHORT).show();
//Does nothing yet ,but soon!
}
});
}
}
8.运行程序
连接手机,运行程序,结果如下图