Android 快捷展示txt文本

核心代码:

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(StringUtils.safeString(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文件夹,注意创建时添加后缀名,添加后缀名,添加后缀名:

效果如下:

发布了8 篇原创文章 · 获赞 5 · 访问量 3619

猜你喜欢

转载自blog.csdn.net/u011065084/article/details/104054908