首页 > 编程技术 > android

Android开发时间日期格式国际化实现方法

发布时间:2016-9-20 20:00

本文章来给大家详细介绍Android开发时间日期格式国际化实现方法,有需要了解日期格式化的朋友可进入参考参考。

DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.

To format a date for the current Locale, use one of the static factory methods:

 代码如下 复制代码
 myString = DateFormat.getDateInstance().format(myDate); 

 

If you are formatting multiple dates, it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.

 代码如下 复制代码

 DateFormat df = DateFormat.getDateInstance(); 
 for (int i = 0; i < a.length; ++i) { 
     output.println(df.format(myDate[i]) + "; "); 
 } 
 

To format a number for a different locale, specify it in the call to getDateInstance:

 代码如下 复制代码

 DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE); 
 


DateFormat can also be used to parse strings:

 代码如下 复制代码
 myDate = df.parse(myString); 

 
例子

 代码如下 复制代码

public static CharSequence formatTimeInListForOverSeaUser(
final Context context, final long time, final boolean simple,
Locale locale) {
final GregorianCalendar now = new GregorianCalendar();
// special time
if (time < MILLSECONDS_OF_HOUR) {
return "";
}
// today
final GregorianCalendar today = new GregorianCalendar(
now.get(GregorianCalendar.YEAR),
now.get(GregorianCalendar.MONTH),
now.get(GregorianCalendar.DAY_OF_MONTH));
final long in24h = time - today.getTimeInMillis();
if (in24h > 0 && in24h <= MILLSECONDS_OF_DAY) {
java.text.DateFormat df = java.text.DateFormat.getTimeInstance(
java.text.DateFormat.SHORT, locale);
return "" + df.format(time);
}
// yesterday
final long in48h = time - today.getTimeInMillis() + MILLSECONDS_OF_DAY;
if (in48h > 0 && in48h <= MILLSECONDS_OF_DAY) {
return simple ? context.getString(R.string.fmt_pre_yesterday)
: context.getString(R.string.fmt_pre_yesterday)
+ " "
+ java.text.DateFormat.getTimeInstance(
java.text.DateFormat.SHORT, locale).format(
time);
}
final GregorianCalendar target = new GregorianCalendar();
target.setTimeInMillis(time);
// same week
if (now.get(GregorianCalendar.YEAR) == target
.get(GregorianCalendar.YEAR)
&& now.get(GregorianCalendar.WEEK_OF_YEAR) == target
.get(GregorianCalendar.WEEK_OF_YEAR)) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("E", locale);
final String dow = "" + sdf.format(time);
return simple ? dow : dow
+ java.text.DateFormat.getTimeInstance(
java.text.DateFormat.SHORT, locale).format(time);
}
// same year
if (now.get(GregorianCalendar.YEAR) == target
.get(GregorianCalendar.YEAR)) {
return simple ? java.text.DateFormat.getDateInstance(
java.text.DateFormat.SHORT, locale).format(time)
: java.text.DateFormat.getDateTimeInstance(
java.text.DateFormat.SHORT,
java.text.DateFormat.SHORT, locale).format(time);
}
return simple ? java.text.DateFormat.getDateInstance(
java.text.DateFormat.SHORT, locale).format(time)
: java.text.DateFormat.getDateTimeInstance(
java.text.DateFormat.SHORT, java.text.DateFormat.SHORT,
locale).format(time);
}

本文章来给大家介绍两段Android实现图片循环播放程序代码,有需要了解的朋友可进入参考。

SDK后个不错的实例

 代码如下 复制代码

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleWithFixedDelay(new runner(), 0, 1, TimeUnit.SECONDS);
//或者用scheduler.scheduleAtFixedRate(new runner(),0,1, TimeUnit.SECONDS);

//接着我们要实现Runnable方法,也就是准时变动现在播放图片的ID

public class runner implements Runnable
{
public void run()

  {

// TODO Auto-generated method stub
currIndex = (currIndex+1)%bitmapId.length;
bofang.this.postInvalidate();//刷新屏幕
}
}

Gallery 中的图片循环播放图片的实现

主要讲的就是一个循环播放图片的实现,我们这里主要还是用到了arraylisy,利用arraylist来控制里面的图片位置,这样就相对简单和容易控制循环了,我们只要牵扯到自定义的arrayadapter还是要注意继承getview在里面设置一个变量参数,就可以来实现变化,这才是最关键的。我们来看看代码吧:

 代码如下 复制代码
public class Splash extends Activity {
ArrayList objects = new ArrayList();
Gallery g;
int i = 0;
@Override
public void onCreate(Bundle icicle) { super.onCreate(icicle);
setContentView(R.layout.photos);
g = (Gallery) findViewById(R.id.gallery);
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
g.setAdapter(new CustomAdapter(this, objects));
g.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView arg0, View arg1,
int arg2, long arg3) {
Log.i(“”, “selected ” + arg2);
}
@Override
public void onNothingSelected(AdapterView arg0) {}
});
}
@Override
public void onBackPressed() {
g.setSelection(i++);
}
private class CustomAdapter extends BaseAdapter {
private Context mCtx;
private List objects;
public int getCount() {
return this.objects.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public CustomAdapter(Context context, ArrayList objects) {
super();
mCtx = context;
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView row = (ImageView) convertView;
if (row == null) {
row = new ImageView(mCtx);
row.setBackgroundDrawable(objects.get(position));
}
return row;
}
}
}

viewpager 循环播放图片 本站有很多种例子了,这里就不介绍了

在安卓手机开发中生成xml文档的文章相对来说比较少,下面我来介绍利用XmlSerializer在安卓中生成xml文档的方法,有需要了解的朋友可参考。

例1

 代码如下 复制代码

try {

  File f = new File(getExternalCacheDir().getAbsolutePath()+"my.xml");
OutputStream outPut = new FileOutputStream(f);

   XmlSerializer serializer=Xml.newSerializer(); 

   serializer.setOutput(outPut, "utf-8"); 

   

   serializer.startDocument("utf-8", true); 

   serializer.startTag(null, "companys"); 

   

   for(String[] s:taxiCompany) 

   { 

      serializer.startTag(null, DBUtil.TAXI_TABLE); 

     

      serializer.attribute(null, DBUtil.KEY_PROVINCE, s[0]); 

      serializer.attribute(null, DBUtil.KEY_CITYNAME, s[1]);

      serializer.attribute(null, DBUtil.KEY_NAME, s[2]); 

      serializer.attribute(null, DBUtil.KEY_TELE, s[3]); 

       

      serializer.endTag(null, DBUtil.TAXI_TABLE); 

   } 

   

   serializer.endTag(null, "companys"); 

   serializer.endDocument(); 

   outPut.close();

  } catch (IOException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

实例2

 代码如下 复制代码

private static void XmlFileCreator(List<JokeBean> data){
        File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/new.xml");
        try{
            if(!newxmlfile.exists())
                newxmlfile.createNewFile();
        }catch(IOException e){
            Log.e("IOException", "exception in createNewFile() method");
        }
        //we have to bind the new file with a FileOutputStream
        FileOutputStream fileos = null;       
        try{
            fileos = new FileOutputStream(newxmlfile);
        }catch(FileNotFoundException e){
            Log.e("FileNotFoundException", "can't create FileOutputStream");
        }
        //we create a XmlSerializer in order to write xml data
        XmlSerializer serializer = Xml.newSerializer();
        try {
            //we set the FileOutputStream as output for the serializer, using UTF-8 encoding
            serializer.setOutput(fileos, "UTF-8");
            //Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null)
            serializer.startDocument(null, Boolean.valueOf(true));
            //set indentation option
            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
          //start a tag called "root"
            serializer.startTag(null, "jokes");
            for(JokeBean joke:data){
                serializer.startTag(null, "joke");
                //i indent code just to have a view similar to xml-tree
                serializer.startTag(null, "id");
                serializer.text(joke.getId());
                serializer.endTag(null, "id");
                                  
                serializer.startTag(null, "title");
                serializer.text(joke.getTitle());
                //set an attribute called "attribute" with a "value" for <child2>
                //serializer.attribute(null, "attribute", "value");
                serializer.endTag(null, "title");
                serializer.startTag(null, "text");
                //write some text inside <text>
                serializer.text(joke.getText());
                serializer.endTag(null, "text");
                                  
                serializer.endTag(null, "joke");
            }
            serializer.endTag(null, "jokes");
            serializer.endDocument();
            //write xml data into the FileOutputStream
            serializer.flush();
            //finally we close the file stream
            fileos.close();
        } catch (Exception e) {
            Log.e("Exception","error occurred while creating xml file");
        }
    }

小编来给大家介绍在android中SharedPreferences进行数据存储实现程序代码,有需要了解的朋友可参考,SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中 重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成

它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存,它是什么样的处理方式呢?SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问,android123提示最 终是以xml方式来保存,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。xml 处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。


这种方式应该是用起来最简单的Android读写外部数据的方法了。他的用法基本上和 J2SE(java.util.prefs.Preferences)中的用法一样,以一种简单、 透明的方式来保存一些用户个性化设置的字体、颜色、位置等参数信息。一般的应用程序都会提供“设置”或者“首选项”的这样的界面,那么这些设置最后就可以 通过Preferences来保存,而程序员不需要知道它到底以什么形式保存的,保存在了什么地方。当然,如果你愿意保存其他的东西,也没有什么限制。只 是在性能上不知道会有什么问题。

实现SharedPreferences存储的步骤如下:

一、根据Context获取SharedPreferences对象

二、利用edit()方法获取Editor对象。

三、通过Editor对象存储key-value键值对数据。

四、通过commit()方法提交数据。


具体代码的书写流程为:

 A、存放数据信息

1、打开Preferences,名称为setting,如果存在则打开它,否则创建新的Preferences

 代码如下 复制代码

SharedPreferences settings = getSharedPreferences(“setting”, 0);

2、让setting处于编辑状态

 代码如下 复制代码

SharedPreferences.Editor editor = settings.edit();

3、存放数据

 代码如下 复制代码

editor.putString(“name”,”ATAAW”);
editor.putString(“URL”,”ATAAW.COM”);

4、完成提交

 代码如下 复制代码

editor.commit();

B、读取数据信息

1、获取Preferences

 代码如下 复制代码

SharedPreferences settings = getSharedPreferences(“setting”, 0);

2、取出数据

 代码如下 复制代码

String name = settings.getString(“name”,”默认值”);
String url = setting.getString(“URL”,”default”);

以上就是Android中SharedPreferences的使用方法,其中创建的Preferences文件存放位置可以在Eclipse中查看:

 代码如下 复制代码

DDMS->File Explorer /<package name>/shared_prefs/setting.xml

 代码如下 复制代码

public class MainActivity extends Activity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //获取SharedPreferences对象
        Context ctx = MainActivity.this;      
        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
        //存入数据
        Editor editor = sp.edit();
        editor.putString("STRING_KEY", "string");
        editor.putInt("INT_KEY", 0);
        editor.putBoolean("BOOLEAN_KEY", true);
        editor.commit();
       
        //返回STRING_KEY的值
        Log.d("SP", sp.getString("STRING_KEY", "none"));
        //如果NOT_EXIST不存在,则返回值为"none"
        Log.d("SP", sp.getString("NOT_EXIST", "none"));
     }
 }

SP.xml文件的具体内容如下:

 代码如下 复制代码

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>2 <map>3 <string name="STRING_KEY">string</string>4 <int name="INT_KEY" value="0" />5 <boolean name="BOOLEAN_KEY" value="true" />6 </map>

本文章来给各位朋友介绍Android中显示网络图片实现代码有需要的朋友可参考参考。

在android当中显示一张网络图片的时候,其实是比较麻烦的。首先得把这个网络图片转换成java的imputstream流,然后再把这个留转换成一个bitMap.
bitMap是可以作为参数传给imageView的。

在下边的returnBitMap函数是最核心的,也是大家可以重用的,它负责把一个url的网络图片变成一个本地的BitMap

 代码如下 复制代码

    package com.jinyan.image; 
   
    import java.io.IOException; 
    import java.io.InputStream; 
    import java.net.HttpURLConnection; 
    import java.net.MalformedURLException; 
   import java.net.URL; 
    
   import android.app.Activity; 
   import android.graphics.Bitmap; 
   import android.graphics.BitmapFactory; 
   import android.os.Bundle; 
   import android.util.Log; 
  import android.view.View; 
   import android.view.View.OnClickListener; 
   import android.widget.Button; 
   import android.widget.ImageView; 
   
  public class ActivityMain extends Activity { 
  /** Called when the activity is first created. */ 
   
  String imageUrl = "http://i.pbase.com/o6/92/229792/1/80199697.uAs58yHk.50pxCross_of_the_Knights_Templar_svg.png"; 
  Bitmap bmImg; 
  ImageView imView; 
   
  Button button1; 
   
   @Override 
   public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
   setContentView(R.layout.main); 
   imView = (ImageView) findViewById(R.id.imview); 
imView.setImageBitmap(returnBitMap(imageUrl)); 



 
public Bitmap returnBitMap(String url) { 
URL myFileUrl = null; 
Bitmap bitmap = null; 
try { 
myFileUrl = new URL(url); 
} catch (MalformedURLException e) { 
e.printStackTrace(); 

try { 
HttpURLConnection conn = (HttpURLConnection) myFileUrl 
  .openConnection(); 
conn.setDoInput(true); 
conn.connect(); 
InputStream is = conn.getInputStream(); 
bitmap = BitmapFactory.decodeStream(is); 
is.close(); 
} catch (IOException e) { 
  e.printStackTrace(); 
  } 
  return bitmap; 

 

 

xml文件

 代码如下 复制代码

   xml version="1.0" encoding="utf-8"?> 
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
   android:orientation="vertical" android:layout_width="fill_parent" 
  android:layout_height="fill_parent"> 
   <ImageView android:id="@+id/imview" android:layout_width="wrap_content" 
   android:layout_height="wrap_content" android:layout_gravity="center" /> 
    LinearLayout> 


注意,想要让你的程序可以访问网络,你必须在menifest文件里边增加:

 代码如下 复制代码

    <uses-permission android:name="android.permission.INTERNET" /> 

标签:[!--infotagslink--]

您可能感兴趣的文章: