我有一个Timepicker空件和一个imagebutton,实现选择好时间,点击imagebutton,到点响铃,请帮我写完整的可以运行的代码
时间: 2023-03-25 18:03:46 浏览: 72
好的,以下是可以实现你要求的代码:
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_launcher" />
</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, "闹钟设置成功", Toast.LENGTH_SHORT).show();
}
});
}
}
```
其中,AlarmReceiver是一个继承BroadcastReceiver的类,用于接收闹钟响铃的广播。你需要在AndroidManifest.xml文件中注册该类。
阅读全文