public class RootActivity extends Activity
{
static LiLa superLayout;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
main();
setContentView(superLayout);
}
private void main()
{
// LiLa is a class which extends LinearLayout
superLayout = new LiLa(this);
//DownloadData is an AsyncTask
DownloadData mDownloadData = new DownloadData(this);
mDownloadData.execute();
}
}
所以AsyncTask改变了superLayout的某些部分,现在在AsyncTak中,我这样做:
RootActivity.superLayout.tv.setText("hello");
改变是否会更好:
static LiLa superLayout;
到
LiLa superLayout;
和:
DownloadData mDownloadData = new DownloadData(this);
到
DownloadData mDownloadData = new DownloadData(this, superLayout);
这样就可以在AsyncTask中执行:
superLayout.tv.setText("hello");
所以问题是:是否更好地访问这种参数(例如TextView tv)或通过静态方式或通过参数更改此TextView的方法?
感谢您阅读。
编辑:顺便说一句,在我的代码中,它有点混乱,可能更像
RootActivity.superLayout.class1.class2.tv.setText("hello");
答案 0 :(得分:2)
最好避免在这种情况下使用static
,如果这意味着您需要将值作为参数传递,那也没关系。 (静态不是O-O,在O-O设计中通常是一个坏主意。它们也会在单元测试中出现问题。)
如果需要,声明所有实例变量并提供getter和/或setter方法通常也是一个好主意。
答案 1 :(得分:1)
我不认为静态访问布局是最好的方法。
更好的解决方案是将布局保存为私有变量,然后将AsyncTask
添加为活动的内部类:
public class RootActivity extends Activity
{
private LiLa superLayout;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
main();
setContentView(superLayout);
}
private void main()
{
// LiLa is a class which extends LinearLayout
superLayout = new LiLa(this);
//DownloadData is an AsyncTask
new DownloadData().execute();
}
private class DownloadData extends AsyncTask<..., ..., ...> {
//You can reference the variable superLayout here.
//If you need the context, use RootActivity.this
}
}
答案 2 :(得分:1)
我认为参数中的访问视图是更好的方式。因此,我们不必为类或活动制作任何静态参考。
答案 3 :(得分:1)