请帮我写完整的可以运行的代码。使用一个Timepicker控件和一个imagebutton实现闹钟功能。
时间: 2023-03-25 09:04:28 浏览: 96
好的,以下是可以运行的代码:
XML布局文件:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/timePicker"
android:layout_centerHorizontal="true"
android:src="@drawable/alarm" />
</RelativeLayout>
```
Java代码:
```
public class MainActivity extends AppCompatActivity {
private TimePicker timePicker;
private ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.timePicker);
imageButton = findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, );
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), , intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "闹钟设置成功", Toast.LENGTH_SHORT).show();
}
});
}
}
```
这段代码使用了一个TimePicker控件和一个ImageButton控件,当用户点击ImageButton时,会获取TimePicker中设置的时间,并使用AlarmManager设置一个闹钟。当闹钟时间到达时,会发送一个广播,由AlarmReceiver接收并处理。
阅读全文