java - FindViewById 在一行中多次

标签 java android textview findviewbyid

这不是问题,更多的是效率问题。我的 Android 应用程序的 XML 布局中有多个 TextView(其中 2 个)。我的问题是,我可以选择多个 TextViews,findViewById 一行中的多个 TextViews 吗?

对我的问题有效吗?

TextView title, darkThemeTitle = findViewById(R.id.title); findViewById(R.id.darkThemeTitle);

最佳答案

当您使用 TextView 标题时,darkThemeTitle = findViewById(R.id.title); findViewById(R.id.darkThemeTitle); 在你的代码中。

  • 此行 TextView title, darkThemeTitle = (TextView) findViewById(R.id.title); 将显示变量 'title' 可能尚未初始化 .So title never initialized in the code .

  • 并且 findViewById(R.id.tab_layout); 将在您的代码中返回 View 并且它从不返回 darkThemeTitle你的代码。

你可以这样做。

 TextView title = (TextView) findViewById(R.id.title); TextView darkThemeTitle = (TextView) findViewById(R.id.darkThemeTitle);

另一种方式

TextView title = null, darkThemeTitle = null;

TextView[] textViews = {title, darkThemeTitle};
Integer[] ids = {R.id.title, R.id.darkThemeTitle};

for (int i = 0; i < textViews.length; i++) {
    textViews[i] = (TextView) findViewById(ids[i]);
}

关于java - FindViewById 在一行中多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47169379/

相关文章:

java - 当我尝试解析字符串时,我的应用程序崩溃了

Android - 如何在工具栏中将标题 (TextView) 居中?

java - Android 文本字段和 TextView 从一个布局到另一个布局

android - 当文本太长时,如何减小 TextView 的大小?

java - Android 以印地语显示结果

java - 交换机不兼容类型错误

java - 如何获取列表中特定类型的所有对象?

java - 当调用新 Intent 上的 startActivity 时,DialogFragment 正在重新启动

android - 如何将 apk 上传到大小超过 100 MB 的 Play 商店?

java - 如何检测 Android 上 Apache SocketClient 中的连接丢失?