1.例子
學習時間函數,並實現了簡單的多個按鈕監聽同一個事件的方法
2.代碼
代碼很簡單,也很清晰
package com.example.datetime;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
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;
public class DatetimeActivity extends Activity implements OnClickListener
{// 注意這裡實現了OnClickListener接口
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datetime);
Button btnShowDate = (Button) findViewById(R.id.btnShowDate);
Button btnShowTime = (Button) findViewById(R.id.btnShowTime);
//注意這裡的監聽器方法
btnShowDate.setOnClickListener(this);
btnShowTime.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
//注意這裡的單擊事件的處理方法
SimpleDateFormat sdf = null;
switch (v.getId())
{
case R.id.btnShowDate:
sdf = new SimpleDateFormat("yyyy-MM-dd");
showDialog("當前日期", sdf.format(new Date()));
break;
case R.id.btnShowTime:
sdf = new SimpleDateFormat("HH:mm:ss");
showDialog("當前時間", sdf.format(new Date()));
break;
}
}
//窗口彈出
private void showDialog(String title, String msg)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(msg);
builder.create().show();
}
}
3.總結
每天寫個例子,保持手感