这不是问题,更多的是效率问题。我的 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' 可能尚未初始化 .Sotitle
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/