从/res/raw中的文本文件填充android片段中的文本视图 [英] populating a text view in an android Fragment from a text file in /res/raw
问题描述
我正在尝试在android片段中填充textview.我根本没有运气,因为片段是空白的.
I am attempting to populate an textview in an android fragment. I am having no luck at all as the fragment is blank.
我知道我从根本上错过了一些东西.我已经阅读了有关碎片的文档,但我仍然感到困惑.
I know I am fundamentally missing something. I have read the docs on fragments and I am still confused.
以下是我对其中一个片段的代码(其他片段看起来相同):
Below is my code for one of the fragments (the others look the same):
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ResourcesFragment extends Fragment {
public ResourcesFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_resources, container, false);
InputStream is = getResources().openRawResource(R.raw.resources);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
String entireFile = "";
try {
while((line = br.readLine()) != null) { // <--------- place readLine() inside loop
entireFile += (line + "\n"); // <---------- add each line to entireFile
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView text = null;
//text.setText(entireFile); // <------- assign entireFile to TextView
//assert text != null;
if (text != null) {
text.setText(entireFile);
}
//return rootView;
return rootView;
}
}
这是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txtsource"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:layout_centerInParent="true"
android:gravity="fill_horizontal|top|left" />
</RelativeLayout>
应用程序编译没有错误**,但是视图为空白.有人可以告诉我正确的方法来做到这一点,不仅可以帮助我了解我出了错的地方,而且可以从程序上正确地做到这一点吗?
the application compiles with no errors**, but the view is blank. Can some one show me the correct way to do this and help me understand not only where I went wrong, but proceduraly, how to do it right??
谢谢.
推荐答案
这是您代码中的错误.因为您忘记了对 TextView
的引用所以添加
here is a bug in your Code. cuz you have forgotten the reference to TextView
so add
TextView文本=(TextView)rootView.findViewById(R.id.txtSource);
然后 text.setText(您的文本!");
希望为您工作:)
这篇关于从/res/raw中的文本文件填充android片段中的文本视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!