1、功能分析
- Layout定义App外观
- 下拉列表列出编程语言的特点
- 点击按钮,开始处理
- 文本框显示推荐的编程语言
- 字符存储在strings.xml
- activity定义App与用户的交互方式
- 定制的Java程序中包含业务逻辑
2、开发视图布局
-
activity_main.xml <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="186dp"
tools:layout_editor_absoluteY="366dp">
<Spinner
android:id="@+id/feature"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/feature"
android:minHeight="32dp" />
<Button
android:id="@+id/find_language"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="@string/find_language" />
<TextView
android:id="@+id/language"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/language" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
-
strings.xml <resources>
<string name="app_name">ProgramAdviser</string>
<string name="find_language">Find Language</string>
<string name="language">Select and Click</string>
<string-array name="feature">
<item>fast</item>
<item>easy</item>
<item>new</item>
<item>OO</item>
</string-array>
</resources>
-
预览
3、按钮事件响应
4、开发模型层
-
ProgramExpert类,和MainActivity同级 public class ProgramExpert {
public String getLangunage(String feature){
String result;
switch (feature){
case "fast":
result = "C/C++";
break;
case "easy":
result = "Python";
break;
case "new":
result = "Kotlin";
break;
case "OO" :
result = "Java";
break;
default:
result = "You got me";
}
return result;
}
}
-
修改MainActivity类 package szst.it.ping.programadviser;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private final ProgramExpert expert = new ProgramExpert();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickButton(View button){
Spinner spinner = findViewById(R.id.feature);
String feature = spinner.getSelectedItem().toString();
String langunage = expert.getLangunage(feature);
TextView textView = findViewById(R.id.language);
textView.setText(langunage);
}
}
5、测试结果
|