【问题标题】:populating a text view in an android Fragment from a text file in /res/raw从 /res/raw 中的文本文件填充 android Fragment 中的文本视图
【发布时间】:2015-08-31 05:32:12
【问题描述】:

我正在尝试在 android 片段中填充文本视图。 因为片段是空白的,所以我一点运气都没有。

我知道我从根本上错过了一些东西。我已经阅读了有关片段的文档,但我仍然感到困惑。

以下是我的其中一个片段的代码(其他片段看起来相同):

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>

应用程序编译没有错误**,但视图为空白。 有人可以告诉我正确的方法来做到这一点,并帮助我不仅了解我哪里出错了,而且在程序上,如何正确地做?

谢谢。

【问题讨论】:

  • 你需要创建一个对TextView的引用,你可以这样做text = (TextView) rootView.findViewById(R.id.txtsource);
  • 创建对 textview 的引用

标签: java android android-fragments android-studio


【解决方案1】:

这是您的代码中的一个错误。因为您忘记了对TextView 的引用 所以添加

TextView text = (TextView) rootView.findViewById(R.id.txtSource); 然后text.setText("your text!");

希望对你有用:)

【讨论】:

  • 哦,是的!像魅力一样工作!谢谢大家!
【解决方案2】:

你忘了找到文本视图:

TextView text = (TextView) rootView.findViewById(R.id.txtSource);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多