CharSequence類型
這是一個接口,代表的是一個有序字符集合,這個接口包含的方法有:charAt(int index),toString(),length(),subSequence(int start,int end).
這里需要說的一點就是,對於一個抽象類或者是接口類,不能使用new來進行賦值,但是可以通過以下的方式來進行實例的創建:
CharSequence cs="hello";
但是不能這樣來創建:
CharSequence cs=new CharSequence("hello");
下面來看看一個例子:
TextView tv; //聲明一個TextView類型的變量tv
CharSequence cs; //聲明一個CharSequence類型的變量cs
String str; //聲明一個字符串類型的str變量
cs=getText(R.string.styled_text); //其實這里使用的this.getText()方法,即指定上下文的方法
tv=(TextView)findViewById(R.id.styled_text); //通過給定的id將tv與對應的組件聯系起來
tv.setText(cs); //使用這句代碼來設置tv的顯示內容
str=getString(R.string.styled_text);
tv=(TextView)findViewById(R.id.plain_text);
tv.setText(str);
Context context=this; //這里使用了Context類型的變量context,指定為當前上下文
Resources res=context.getResources(); //定義一個Resources類型的變量res,並給它賦值
cs=res.getText(R.string.styled_text); //獲得R類中指定變量的值
tv=(TextView)findViewById(R.id.styled_text); //同上
tv.setText(cs); //設置值
下面來看看如何在Android應用程序中訪問文件應用程序包中的資源
AssetManager類,即管理資產類,這個類為訪問當前應用程序的資產文件提供了入口。
這個類的方法有:open (String filename,int accessMode)使用一個精確的訪問模式來打開當前包的一個資產,
返回輸入流,即由此讀取了這個包的資產的內容。要注意的是,這里所說的資產是放置在assets目錄下的文件資產。
其中accessmode的值可以為:ACCESS_BUFFER,ACCESS_RANDOM,ACCESS_STREAMING,ACCESS_UNKNOWN其中的一個。
下面給出一個實例:
InputStream is=getAssets().open(String filename);//從指定的filename文件中讀取內容,並將其放入到InputStream類型的is變量中
int size=is.available(); //獲取流的長度
byte[] buffer=new byte[size]; //定義流長度的字節數組
is.read(buffer); //將流中的內容放到buffer數組中
is.close();
String text=new String(buffer);
TextView tv=(TextView)findViewById(R.id.text);
tv.setText(text); //同上
Android 除了提供/res目錄存放資源文件外,在/assets目錄也可以存放資源文件,而且/assets目錄下的資源文件不會在R.java自動生成ID,所以讀取/assets目錄下的文件必須指定文件的路徑。我們可以通過AssetManager 類來訪問這些文件。
比如我要讀取/assets/background.png
- Bitmap bgImg = getImageFromAssetFile( "background.png" );
- Bitmap bgImg = getImageFromAssetFile("background.png");
- private Bitmap getImageFromAssetFile(String fileName){
- Bitmap image = null ;
- try {
- AssetManager am = context.getAssets();
- InputStream is = am.open(fileName);
- image = BitmapFactory.decodeStream(is);
- is.close();
- }catch (Exception e){
- }
- return image;
- }