Guna Chand
Guna Chand

Reputation: 41

How to set the current date as the title in the title bar?

I want to set the current date as the title in the title bar and make it responsive, if i click on title (the current date), then a calendar dialog will appear to set the date and according to the chosen date i have to display the data. I tried adding text view to the title bar. But i didn't got that

Upvotes: 0

Views: 810

Answers (1)

Anirban Roy
Anirban Roy

Reputation: 180

First of all set the Toolbar in your layout xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="8dp"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

Then in your Activity class, get the Current date and set as the title

String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

ToolBar mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar);            
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle(date); //This is to set the current date as title

DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        // TODO Auto-generated method stub
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        updateLabel();
    }
};

mActionBarToolbar.findViewById(R.id.toolbar_title).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG,"Clicked");
             new DatePickerDialog(classname.this, date, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

Add this method to the activity -

private void updateLabel() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    mActionBarToolbar.setText(sdf.format(myCalendar.getTime()));
}

Upvotes: 0

Related Questions