我在不同的活动中调用了一些TextViews的setText(),所以我应该为此定义一个函数。
在我的OnCreate方法中,我使用以下代码来调用函数:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myAct);
View inflatedView = (this.getLayoutInflater()).inflate(R.layout.activity_myAct, null);
InputStream is = getResources().openRawResource(R.raw.textfile);
ReadFile rf = new ReadFile();
rf.OpenWithTitles(getApplicationContext(), inflatedView, is, "Titles", "Texts", this.getPackageName());
我的OpenWithTitles功能如下:
public void OpenWithTitles(Context context, View inflatedView, InputStream is, String title, String text, String packName){
//Open text files with Titles on one line and one empty line before next Title.
id = 0;
boolean nextTitle = true;
try {
StringBuilder fileText = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null){
if (nextTitle){
id++;
fileText.append(line);
SetTextView(context, inflatedView, title, packName, fileText);
nextTitle = false;
}
else if (line.length()==0) { //Empty lines between titles
fileText.setLength(fileText.length()-1);
SetTextView(context, inflatedView, text, packName, fileText);
nextTitle = true;
}
else {
fileText.append(line);
fileText.append('\n');
}
}
SetTextView(context, inflatedView, text, packName, fileText);
br.close();
}
catch (IOException e){
e.printStackTrace();
}
}
和SetTextView函数如下:
public void SetTextView(Context context, View inflatedView, String idName, String packName, StringBuilder text){
((TextView)inflatedView.findViewById(context.getResources().getIdentifier(idName + id, "id", packName))).setText(text);
text.setLength(0);
}
我已经正确定义了我的android:id&(检查了dubble和tripple) 我已经使用Log.d打印并检查SetTextView函数中返回的标识符,并通过打开R.java文件手动检查了R.java中该idName + id的相同值。我还使用获得的值的ResourceName()检查了这一点 我检查了文本(要设置)以查看它是否包含正确的文本(它确实如此) 我检查了idName + id并将它们与.xml文件进行了比较 并且它不会返回任何错误,它会运行并打开活动,但文本不会显示。 (如果我在xml文件中添加android:text,它会显示文本)。
答案 0 :(得分:0)
您正在为此行中的布局充气:
View inflatedView = (this.getLayoutInflater()).inflate(R.layout.activity_myAct, null);
但您未在Activity
中使用它。您正在此处为您的内容设置XML文件:
setContentView(R.layout.activity_quran);
您应该将Activity
传递给您的方法,因此请更改:
rf.OpenWithTitles(getApplicationContext(), inflatedView, is, "Titles", "Texts", this.getPackageName());
到此:
rf.OpenWithTitles(getApplicationContext(), this, is, "Titles", "Texts", this.getPackageName());