请帮我写完整的可以运行的代码。使用一个Timepicker控件和一个imagebutton实现闹钟功能。
时间: 2023-03-25 12:04:27 浏览: 83
Python编写一个闹钟功能
好的,以下是可以运行的代码:
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/ic_alarm"
android:contentDescription="@string/alarm_button_description"/>
</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(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, , intent, );
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(MainActivity.this, "Alarm set for " + hour + ":" + minute, Toast.LENGTH_SHORT).show();
}
});
}
}
```
请注意,这只是一个简单的示例代码,您可以根据您的需求进行修改和扩展。
阅读全文