Skip to main content

WeekView in Android

Hello Friends,   
Have you Searching for Android calender with WeekView. 
Today I am sharing android tutorial for android custom calendar WeekView.

WeekView.java


public class WeekView extends ActionBarActivity implements OnItemClickListener, OnClickListener {

private GridView mGrid;
private GregorianCalendar mCalendar;
private Date[] mWeek;
private TextView mMonthText;
private RelativeLayout mArrowRight;
private RelativeLayout mArrowLeft;
private CalendarAdapter mAdapter;
private SimpleDateFormat mFormatMonth = new SimpleDateFormat("MMMM");
private SimpleDateFormat mFormatDay = new SimpleDateFormat("d");
private SimpleDateFormat mFormatYear = new SimpleDateFormat("yyyy");

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_week_view);

mGrid=(GridView)findViewById(R.id.gridview);
mGrid.setOnItemClickListener(this);

mMonthText=(TextView)findViewById(R.id.title);
mArrowLeft=(RelativeLayout)findViewById(R.id.previous);
mArrowLeft.setOnClickListener(this);

mArrowRight=(RelativeLayout)findViewById(R.id.next);
mArrowRight.setOnClickListener(this);

mCalendar = (GregorianCalendar)GregorianCalendar.getInstance();
mCalendar.setTime(new Date());
mCalendar.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.SUNDAY);
//mCalendar.add(Calendar.DAY_OF_YEAR, -7);
mCalendar.add(Calendar.DAY_OF_YEAR, 0);

mWeek=new Date[7];
   for(int i=0;i<7;i++)
   {
    mWeek[i]=mCalendar.getTime();
    //mCalendar.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.SUNDAY);
    mCalendar.add(Calendar.DAY_OF_YEAR, 1);
   }
   setSelectedMonthText();

   mAdapter=new CalendarAdapter(this, mWeek);
   
   mGrid.setAdapter(mAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.week_view, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}


private void setSelectedMonthText() {
String monthText;
if(Integer.parseInt(mFormatDay.format(mWeek[0]))>Integer.parseInt(mFormatDay.format(mWeek[6])))
monthText=mFormatMonth.format(mWeek[0])+" / "+mFormatMonth.format(mWeek[6]);
else
monthText=mFormatMonth.format(mWeek[0]);

mMonthText.setText(monthText+" "+mFormatYear.format(mWeek[6]));
}

private void addWeek()
{
for(int i=0;i<7;i++)
{
mWeek[i]=mCalendar.getTime();
    mCalendar.add(Calendar.DAY_OF_YEAR, 1);
}

mAdapter.notifyDataSetChanged();

setSelectedMonthText(); 
//clearBackground();
}


private void subWeek()
{
mCalendar.add(Calendar.DAY_OF_YEAR, -14);
for(int i=0;i<7;i++)
{
    mWeek[i]=mCalendar.getTime();
    mCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
setSelectedMonthText();
mAdapter.notifyDataSetChanged();

//clearBackground();
}


@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.previous:
subWeek();
break;
case R.id.next:
addWeek();
break;
}
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub

}

}


activity_week_view.xml:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/calendar_top" >

        <RelativeLayout
            android:id="@+id/previous"
            android:layout_width="40dip"
            android:layout_height="30dip"
            android:layout_alignParentLeft="true" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/arrow_left" />
        </RelativeLayout>

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dip"
            android:textColor="#000000"
            android:textSize="18dip"
            android:textStyle="bold" />

        <RelativeLayout
            android:id="@+id/next"
            android:layout_width="40dip"
            android:layout_height="30dip"
            android:layout_alignParentRight="true" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:background="@drawable/arrow_right" />
        </RelativeLayout>
    </RelativeLayout>

    <GridView
        android:id="@+id/gridview"
        android:layout_below="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:listSelector="@android:color/transparent"
        android:numColumns="7"
        android:stretchMode="columnWidth" />
    
    <LinearLayout 
        android:id="@+id/text"
        android:layout_below="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       
    </LinearLayout>

</RelativeLayout>


CalendarAdapter.java


public class CalendarAdapter extends BaseAdapter{
private Context mContext;
    private Date[]   mWeek;
    private SimpleDateFormat mFormatNumber;
    private View previousView;
public CalendarAdapter(Context _context, Date[] _week) {
Locale.setDefault(Locale.US);
mContext = _context;
       mWeek = _week;
       mFormatNumber = new SimpleDateFormat("d");
}
private static class ViewHolder {
        public TextView tvNumber;
    }

@Override
public int getCount() {
return mWeek.length;
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
        if (convertView == null) {
        LayoutInflater vi = (LayoutInflater)this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.calendar_item, null);
        holder = new ViewHolder();
        holder.tvNumber = (TextView)  convertView.findViewById(R.id.tv_number);
        convertView.setTag(holder);
        } else {
        holder = (ViewHolder) convertView.getTag();
        }
        
        holder.tvNumber.setText(mFormatNumber.format(mWeek[position]));
        return convertView;
}

public View setSelected(View view) {
if (previousView != null) {
previousView.setBackgroundResource(R.drawable.list_item_background);
}
previousView = view;
view.setBackgroundResource(R.drawable.calendar_cel_selectl);
return view;
}

}


calendar_item.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/calendar_cell"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="2dip" >

    <TextView
        android:gravity="center"
   android:id="@+id/tv_number"
   android:background="@null"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0000D7"
        android:textSize="14sp"
        android:textStyle="bold" >
    </TextView>
</LinearLayout>


Screenshot:




here is the Sample Code





Comments

Popular posts from this blog

How to check internet connectivity in Android app using BroadcastReceiver

So let's get started with How to check internet connectivity in Android using BroadcastReceiver. For this post I'm using Kotlin language. Well lots of people are using simple method to get network connectivity using ConnectivityManager. But using that approach we will get network state only when we are calling that method. So how would I know that network state changed. This will achieved using BroadcastReceiver.  What is BroadcastReceiver? BroadcastReceiver uses Publish-Subscribe pattern. Android app can send and receive messages from Android system and other apps.  Android system sends broadcast when various system events occurred like device charging, network state changes. Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically routes broadcasts to apps that have subscribed to receive that particular type of broadcast. So for this scenario we need to add some changes in AndroidManifest.xml file - ...

RxJava introduction for Android developer

RxJava is Java implementation of Reactive Extension. Basically it’s a library that composes asynchronous events by following Observer Pattern. You can create asynchronous data stream on any thread, transform the data and consumed it by an Observer on any thread. The library offers operators like map, combine, merge, filter and lot more that can be applied onto data stream.  Below are the list of schedulers available and their brief introduction. - Schedulers.io()  – This is used to perform non CPU-intensive operations like making network calls, reading disc / files, database operations etc., This maintains pool of threads. 

 - AndroidSchedulers.mainThread()  – This provides access to android Main Thread / UI Thread. Usually operations like updating UI, user interactions happens on this thread. We shouldn’t perform any intensive operations on this thread as it makes the app glitchy or ANR dialog can be thrown. 

 - Schedulers.newThre...

Get domain name from URL in android

Sample Code: String url="http://sports.in.msn.com/football-world-cup-2014/world-cup-animals-5"; String hostName=getDomainName(url); private CharSequence getDomainName(String shareURL) throws URISyntaxException {    URI uri = new URI(shareURL);    String domain = uri.getHost();     return domain; } above method return host name from given URL. You can get more from URL using below methods. uri.getProtocol(); uri.getAuthority(); uri.getHost(); uri.getPort(); uri.getPath(); uri.getQuery(); uri.getFile(); Output: protocol = http authority = sports.in.msn.com host = sports.in.msn.com port = -1 path = /football-world-cup-2014/world-cup-animals-5 query = null filename = /football-world-cup-2014/world-cup-animals-5