我已经为Android应用编写了一个代码,可以输入时间并在其上生成警报。
最初,我已经为输入时间添加了两个按钮,并为set alarm
添加了一个按钮。
现在,我想改进我的方法,即想要删除设置警报按钮和时间设置按钮以文本形式而不是TimePicker
输入时间。
为此,我为ListView Array Adapter
编写了一个代码,这样我只能输入两次,并且输入时间可以存储在该数组Adapter
中以进行报警服务。但不幸的是,不得不面对很多困难。现在我应该在代码/方法中做出哪些更改,以更好的方式改进它。
我的简单代码:
package com.task;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Calendar Alarm = Calendar.getInstance();
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1= (Button)findViewById(R.id.b1);
b1.setOnClickListener(this);
b2= (Button)findViewById(R.id.b2);
b2.setOnClickListener(this);
Button alrm= (Button)findViewById(R.id.alrm);
alrm.setOnClickListener(this);
}
@Override
public void onClick(View clickedView) {
if ((clickedView.getId() == R.id.b1) ||
(clickedView.getId() == R.id.b2)
{
TimePickerDialog t= new TimePickerDialog(this, timeSetListener, Calendar.getInstance().get(Calendar.HOUR), Calendar.getInstance().get(Calendar.MINUTE), false);
t.show();
}
else if (clickedView.getId() == R.id.alrm)
{
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, Recv.class);
PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), (int) System.currentTimeMillis(), intent, 0); // Unique value for every Alarm
Alarm.set(Calendar.SECOND, 0);
Alarm.set(Calendar.MILLISECOND, 0);
am.set( AlarmManager.RTC_WAKEUP, Alarm.getTimeInMillis(), pi);
}
}
TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
Alarm.set(Calendar.HOUR, hour);
Alarm.set(Calendar.MINUTE, minute);
}
};
}
我的ListView代码(尝试):
public class MainActivity extends ListActivity {
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int x=0; x<=2; x++) // loop for iterating array members
{
Button btn = (Button) findViewById(R.id.btnAdd);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
setListAdapter(adapter);
}
}
}