【问题标题】:How to set the current date as the title in the title bar?如何将当前日期设置为标题栏中的标题?
【发布时间】:2018-09-23 16:14:26
【问题描述】:

我想将当前日期设置为标题栏中的标题并使其具有响应性,如果我单击标题(当前日期),则会出现一个日历对话框来设置日期并根据我选择的日期必须显示数据。我尝试将文本视图添加到标题栏。但是我没听懂

【问题讨论】:

    标签: android date android-calendar android-date android-titlebar


    【解决方案1】:

    首先在你的布局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"/>
    

    然后在您的 Activity 类中,获取当前日期并设置为标题

    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();
            }
        });
    

    将此方法添加到活动中 -

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

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多