内容
一个抽奖小app来体验Java设计程序
首先在
在箭头所示位置,写如下代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<!--文本框-->
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#2F2E2F"
android:text="敌敌畏"
android:textColor="#FFF"
android:textSize="30sp"
android:gravity="center"
/>
<!--按钮-->
<Button
android:layout_width="match_parent"
android:layout_height="65dp"
android:background="#D65489"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="开始抽奖"
android:textColor="#fff"
android:textSize="20sp"
android:onClick="start"
/>
</LinearLayout>
然后在
箭头所示位置,写如下的代码
package swu.ljh.luckymanoh;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.lang.*;
import java.util.*;
public class MainActivity extends AppCompatActivity {
//准备候选人,用数组来表示
String[] names = new String[]{"李四","张三","王五"};
Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//按钮的点击事件
public void start(View view) {
//将View转化为Button
Button btn = (Button)view;
//获取当前的标题
String title = btn.getText().toString();
//判断按钮的标题
if(title.equals("开始抽奖")){
//设置为暂停
btn.setText("暂停");
//创建定时器
timer = new Timer();
//每隔一段事件去执行一个任务
timer.schedule(new TimerTask() {
@Override
public void run() {
produceOnePeople();
}
},0,50);
}else{
//设置为开始抽奖
btn.setText("开始抽奖");
//关闭定时器
timer.cancel();
}
produceOnePeople();
}
//产生一个随机的人名,显示到文本控件上
public void produceOnePeople(){
//1.产生一个随机数
Random random = new Random();
int index = Math.abs(random.nextInt()) % names.length;//产生 0到数组个数-1 的随机数
//2.从数组里面取出这个名字
String name = names[index];
//3.将名字显示到文本框上
TextView tv = findViewById(R.id.tv_name);
tv.setText(name);
}
}
这样就完成了整个程序的代码
在手机上大概是这样的
总结
今天主要是感知一下用Java来设计程序,其实这个小app还是很有意思的,我可以随便改人名,甚至还可以改成别的东西。这个小demo也激发了我继续学Java的兴趣。