简体   繁体   English

Android中的TextView.setText

[英]TextView.setText in Android

I'm new to Android development and I want to understand how TextView.setText method works.我是 Android 开发新手,我想了解 TextView.setText 方法的工作原理。 In this example,在这个例子中,

private TrueFalse[] mQuestionBank = new TrueFalse[]
        {
                new TrueFalse(R.string.question_oceans, true),
                new TrueFalse(R.string.question_mideast, false),
                new TrueFalse(R.string.question_africa, false),
        };

private  int mCurrentIndex = 0;
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);

The point I can't understand is how can setText return question text by only getting an int?我无法理解的一点是 setText 如何仅通过获取 int 来返回问题文本? How can an int be sufficient? int 怎么可能就足够了? Could you explain that to me?你能给我解释一下吗? Thanks.谢谢。

When you add a String to the String files it generate a reference in the R file and this reference is a int and it can be used on the code and in the xml file like:当你将一个字符串添加到字符串文件时,它会在 R 文件中生成一个引用,这个引用是一个 int,它可以在代码和 xml 文件中使用,如:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/question_oceans" />

The reference of the String "R.string.question_oceans" in the R file is an int, so SetText can accept int (from the reference) and can accept a real Strings like "my string". R文件中字符串“R.string.question_oceans”的引用是一个int,所以SetText可以接受int(来自引用)并且可以接受像“我的字符串”这样的真实字符串。

int here, is the id of String value which defined in the string.xml.这里的int,是string.xml中定义的String值的id。 So textView.setText(int resid) get value as string then set internally.所以 textView.setText(int resid) 获取值作为字符串然后在内部设置。

Here's the source code of TextView.这是 TextView 的源代码。

public final void setText(CharSequence text) {
        setText(text, mBufferType);
}

// So this get string value from resources and use the above setText().
public final void setText(int resid) {
    setText(getContext().getResources().getText(resid));
}

You can avoid getting string value from resources and make your code simpler.您可以避免从资源中获取字符串值并使您的代码更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM