我想基于3个不同的日期阶段(早上,下午,晚上)设置自定义文本视图
那样:
if (morning) {
mText.setText("it's morning!");
}
和下午和晚上一样。那可能吗? 谢谢
答案 0 :(得分:3)
使用
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String str = sdf.format(new Date());
String[] hr=str.split(":");
int hr1=Integer.parseInt(hr[0]);
if(hr1<12)
{
mText.setText("it's morning!");
}else if(hr1>12&& hr1<17)
{
mText.setText("it's afternoon!");
}elseelse if(hr1>17&& hr1<20)
{
mText.setText("it's evening!");
}
答案 1 :(得分:1)
当然这是可能的。你没有问更多问题......
答案 2 :(得分:1)
使用此代码可以帮助您
XML
<RelativeLayout 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:id="@+id/relative">
</RelativeLayout>
Android代码
package com.example.dynamic;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss a");
//get current date time with Date()
Date date = new Date();
String tim =dateFormat .format(new Date());
String[] hr=tim.split(":");
String s1="";
int hour=Integer.parseInt(hr[0]);
//Toast.makeText(getBaseContext(), hr1, Toast.LENGTH_SHORT).show();
if(hour<12)
{
// mText.setText("it's morning!");
s1= "it's morning!";
}else if(hour>12&& hour<17)
{
//mText.setText("it's afternoon!");
s1= "it's afternoon!";
}
else if(hour>17&& hour<20)
{
//mText.setText("it's evening!");
s1= "it's evening!";
}
System.out.println(dateFormat.format(date));
RelativeLayout rl=(RelativeLayout) findViewById(R.id.relative);
TextView textDynamic = new TextView(this);
textDynamic.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
textDynamic.setText(s1);
textDynamic.setBackgroundColor(Color.GREEN);
textDynamic.setTextColor(Color.RED);
textDynamic.setTextScaleX(2);
textDynamic.setTextSize(20);
textDynamic.isClickable();
textDynamic.setPadding(10, 10, 10, 10);
rl.addView(textDynamic);
}
}