在这两种选择中,在下面的示例中,放置 View 类的变量的最佳位置是哪个?在这个 android 应用程序代码中,最好将其作为扩展活动的类的全局变量,还是在名为 ImageAdapter 的嵌套内部类中声明扩展 BaseAdapter 的变量更好?
哪个更好?
2个代码示例如下所示。
在第一个示例中,View 类的视图变量在范围内被声明为更具全局性。如此处所示,它出现在 Main 类中。
public class Main extends Activity {
View view; // <--- PLACEMENT IN A MORE GLOBAL POSITION
Cursor imageCursor;
public class ImageAdapter extends BaseAdapter {
private Context context;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapterview, null);
}else{
view = convertView;
}
在第二个示例中,视图视图被声明为 ImageAdapter 类的局部变量,在该类的 getView 方法内。
public class Main extends Activity {
Cursor imageCursor;
public class ImageAdapter extends BaseAdapter {
private Context context;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view; // <--- PLACEMENT AS LOCAL VARIABLE
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapterview, null);
}else{
view = convertView;
}