安卓 用Studio來完成一個最理想的時間選擇器
阿新 • • 發佈:2019-02-16
相信安卓時間選擇器大家並不陌生吧,下面我們一起來看看最簡單最理想的一個:
1.直接看看效果圖吧(下載連結在最後):
2.程式碼如下:
Mainactivity:
package com.example.administrator.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.Calendar; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import org.feezu.liuli.timeselector.TimeSelector; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { int mYear, mMonth, mDay; Button btn; TextView dateDisplay; final int DATE_DIALOG = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); initData(); final Calendar ca = Calendar.getInstance(); mYear = ca.get(Calendar.YEAR); mMonth = ca.get(Calendar.MONTH); mDay = ca.get(Calendar.DAY_OF_MONTH); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG: return new DatePickerDialog(MainActivity.this, mdateListener, mYear, mMonth, mDay); } return null; } DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; display(); } /** * 設定日期 利用StringBuffer追加 */ private void display() { dateDisplay.setText(new StringBuffer().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" ")); } }; private void initData() { //監聽事件 btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(DATE_DIALOG); } }); } private void init() { btn = (Button) findViewById(R.id.dateChoose); dateDisplay = (TextView) findViewById(R.id.dateDisplay); } }
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.administrator.myapplication.MainActivity"> <TextView android:id="@+id/dateDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我是預設時間顯示" android:layout_marginTop="151dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <Button android:id="@+id/dateChoose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="選擇日期" android:layout_below="@+id/dateDisplay" android:layout_centerHorizontal="true" android:layout_marginTop="15dp" /> </RelativeLayout>
點選下載:http://download.csdn.net/my
當然,就是這麼簡單,希望大家用的上