Android 快捷展示txt文本

本文介绍了一种在Android应用中加载并显示raw资源的方法。通过继承AppCompatActivity并重写onCreate方法,设置布局并初始化视图,从raw资源中读取数据并显示在TextView上。示例展示了如何创建一个具体的Activity来加载特定的raw资源。

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

核心代码:

activity_raw.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">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:text="Hello World!"
            android:textSize="18sp" />

    </androidx.core.widget.NestedScrollView>

</LinearLayout>
public abstract class RawActivity extends AppCompatActivity {

    private final int rawId;
    private final String title;

    public RawActivity(int rawId, String title) {
        this.rawId = rawId;
        this.title = title;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_raw);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(title);
            //左侧按钮:可见+可用+更换图标
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
        initView();
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return super.onSupportNavigateUp();
    }

    private void initView() {
        TextView textView = findViewById(R.id.tvTxt);
        try {
            InputStream is = getResources().openRawResource(rawId);
            byte[] bytes = new byte[is.available()];
            int len = is.read(bytes);
            if (len != 0) {
                String rawTxt = new String(bytes);
                textView.setText(rawTxt);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

使用:

public class FactoryActivity extends RawActivity {
    public FactoryActivity() {
        super(R.raw.factory, "工厂模式");
    }
}

在res目录下创建raw文件夹,注意创建时添加后缀名,添加后缀名,添加后缀名:

效果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值