2013年9月23日 星期一

CalendarView


在Android 3.0 之後支援CalendarView,可以簡單設計日曆的View

在layout 設計

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <CalendarView
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

Activity 中以 cv=(CalendarView)findViewById(R.id.cv);  得到CalendarView,在OnDateChangeListener  必須實作 onSelectedDayChange(CalendarView view, int year, int month,int dayOfMonth)。
因onSelectedDayChange 在日期變化才會有變動,因此可加入一init 的預設值

程式如下

public class MainActivity extends Activity {
private CalendarView cv;
private TextView tv;
    int Myear,Mmonth,Mday;
 
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.tv);
init();
cv=(CalendarView)findViewById(R.id.cv);
cv.setOnDateChangeListener(listener);
// cv.setOnClickListener(l);

}

public void init()
{
Calendar c=Calendar.getInstance();
int year=c.get(Calendar.YEAR);
int Mmonth=c.get(Calendar.MONTH);
int Mday=c.get(Calendar.DATE);
tv.setText(new StringBuilder().append(year)
.append("-").append(Mmonth).append("-").append(Mday));
}

OnDateChangeListener listener=new OnDateChangeListener() {

@Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
// TODO Auto-generated method stub
Myear = year;
Mmonth = month;
Mday = dayOfMonth;
tv.setText(new StringBuilder().append(year)
.append("-").append(Mmonth).append("-").append(Mday));
}
};



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

程式下載

沒有留言:

張貼留言