第61章、资源文件之存取操作(从零开始学Android)

本文详细介绍了在Android开发中如何使用布局文件设计界面,并通过Java代码读取资源文件的具体步骤。包括创建按钮和文本视图,使用openRawResource()方法读取资源文件内容,并显示在界面上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  Android资源主要包括文本字符串(strings)、颜色(colors)、数组(arrays)、动画(anim)、布局(layout)、图像和图标(drawable)、音频视频(media)和其他应用程序使用的组件。

  本章着重讲解一下关于资源文件的存储操作。

一、设计界面

  1、布局文件

  打开activity_main.xml文件。

  输入以下代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取资源文件(Raw)" />

    <TextView
        android:id="@+id/cont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


二、程序文件

  打开“src/com.genwoxue.fileresources/MainActivity.java”文件。

  然后输入以下代码:

package com.genwoxue.fileresources;


import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.content.res.Resources;

public class MainActivity extends Activity {

	private Button btnRead=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btnRead=(Button)super.findViewById(R.id.read);
		
		//读取资源文件
		btnRead.setOnClickListener(new OnClickListener(){
			public void onClick(View v)
        	{
				//获取资源对象
				Resources res=MainActivity.this.getResources();			
				//通过openRawResource()读取资源为R.raw.friend的资源文件,结果返回到InputStream
				InputStream input=res.openRawResource(R.raw.friend);	
				//读取资源文件内容
				Scanner scan=new Scanner(input);
				StringBuffer info=new StringBuffer();
				while(scan.hasNext())
					info.append(scan.next()).append("\n");
				scan.close();
				
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				Toast.makeText(getApplicationContext(), info.toString(),Toast.LENGTH_LONG).show();
        	}
		});
		
	}
}


三、资源文件

  我们把文件friend.txt保存到res/raw文件夹中。

  注意:raw文件不存在,需要你手动创建。

  

四、运行结果

  

转载于:https://my.oschina.net/u/2252134/blog/545667

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值