每隔一段时间,进入一个新的 Activity 就需要更新几个 TextView
中的值。假设我有 n 个 String 要在启动 Activity 的 n 个 TextView 中写入。
哪一种是保证良好性能并提供“干净代码”的最佳方法?
变体 1(我实际应用的方式):
我将单个 TextView
变量“tempText”声明为全局变量,并将要更新的 TextView 分配给该变量(或者在额外的方法中)。
或者,a) 在 onCreate()
中执行整个过程,而 b) 则在名为 e.g. 的方法中处理所有内容。 updateTextViews()
(...)
public class MyActivity extends Activity{
private TextView tempText;
public onCreate(Bundle icicle){
(...)
tempText = (TextView) findViewById(R.id.tv_1);
tempText.setText(string_1);
tempText = (TextView) findViewById(R.id.tv_2);
tempText.setText(string_2);
(...)
tempText = (TextView) findViewById(R.id.tv_n);
tempText.setText(string_n);
}
}
变体 2: 我将单个 TextView 变量“tempText”声明为 onCreate() 或相应方法中的变量,并将要更新的 TextView 分配给该变量。 其余部分与变体 1 类似。
(...)
public class MyActivity extends Activity{
public onCreate(Bundle icicle){
(...)
private TextView tempText;
tempText = (TextView) findViewById(R.id.tv_1);
tempText.setText(string_1);
tempText = (TextView) findViewById(R.id.tv_2);
tempText.setText(string_2);
(...)
tempText = (TextView) findViewById(R.id.tv_n);
tempText.setText(string_n);
}
}
变体 3:
我为每个要更新的 TextView
声明了一个全局 TextView
变量。据我所知,这需要更多的 RAM 空间,但我不知道对速度的影响。另外,在 onCreate()
(a)) 或单独的方法 (b)) 中处理它之间有区别吗?
(...)
public class MyActivity extends Activity{
private TextView tempText_1;
private TextView tempText_2;
(...)
private TextView tempText_n;
public onCreate(Bundle icicle){
(...)
tempText_1 = (TextView) findViewById(R.id.tv_1);
tempText_1.setText(string_1);
tempText_2 = (TextView) findViewById(R.id.tv_2);
tempText_2.setText(string_2);
(...)
tempText_n = (TextView) findViewById(R.id.tv_n);
tempText_n.setText(string_n);
}
}
变体 4:
我为每个 TextView
声明一个 TextView
变量,以在 onCreate()
或处理此问题的相应方法中进行更新。其余的与变体 3 类似?
(...)
public class MyActivity extends Activity{
public onCreate(Bundle icicle){
(...)
private TextView tempText_1;
private TextView tempText_2;
(...)
private TextView tempText_n;
tempText_1 = (TextView) findViewById(R.id.tv_1);
tempText_1.setText(string_1);
tempText_2 = (TextView) findViewById(R.id.tv_2);
tempText_2.setText(string_2);
(...)
tempText_n = (TextView) findViewById(R.id.tv_n);
tempText_n.setText(string_n);
}
}
哪一种是“最好”的方法?变体 1 和 2 只在 RAM 中保留一个内存地址并使用它,而根据 Robert C. Martins 的“Clean Code”,这些变量确实是不明确的。选项 3 和 4 正好相反。但对于其余的,我不太清楚其他影响。
最佳答案
就个人而言,如果我需要在 Activity 中的其他位置再次访问 TextView(即在 onResume 中,这是我通常放置静态 UI 更新的位置),我会使用变体 3。如果 setText 是一次性的事情,我会做类似的事情 -
((TextView) findViewById( R.id.tv_1 ) ).setText( string_1 );
((TextView) findViewById( R.id.tv_2 ) ).setText( string_2 );
如果怀疑 View 可能不存在(即当您在开发期间修改布局时),我会使用包装器,例如 --
private void safeSetText( int id, String caption ) {
TextView tv = (TextView) findViewById( id );
if( tv != null )
tv.setText( caption );
else
Log.d( "..... " );
}
然后在onCreate中: safeSetText( R.id.tv_1, string_1 ); safeSetText( R.id.tv_2, string_2 );
关于android - 在 Android 中干净地声明和使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12842331/