创建一个接受活动引用的 UIHelper 类是不是一个坏主意?我试图理解和避免内存泄漏,我读过的最大问题之一是不传递上下文。我有这个 UIHelper 类,它引用一个活动并将 TextView 和 EditView 对象构建/返回给我的活动。我在想这会阻止我的活动被 GC'ed 但我不确定。有没有更合适的方法来做到这一点?
这是我的 UIHelper 类
public class UIHelper {
private Activity activity;
private LinearLayout.LayoutParams inputParms = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
private LinearLayout.LayoutParams labelParms = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
private LinearLayout.LayoutParams valueParms = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
private static String[] USStates;
public UIHelper(Activity activity){
this.activity = activity;
this.USStates = activity.getResources().getStringArray(R.array.USStates);
labelParms.setMargins(5, 5, 0, 0);
inputParms.setMargins(5, 2, 0, 12);
}
public View buildEditView(RecordItem recordItem){
String type = recordItem.getType();
if(type.equalsIgnoreCase("text") || type.equalsIgnoreCase("phone") || type.equalsIgnoreCase("integer")){
EditText vTextInput = new EditText(activity);
vTextInput.setTextSize(20);
vTextInput.setLayoutParams(inputParms);
if (type.equalsIgnoreCase("integer")) {
vTextInput.setInputType(InputType.TYPE_CLASS_NUMBER);
} else if (type.equalsIgnoreCase("phone")) {
vTextInput.setInputType(InputType.TYPE_CLASS_PHONE);
}
if (!recordItem.getDisplay()) {
vTextInput.setVisibility(View.GONE);
}
vTextInput.setSingleLine();
recordItem.setEditView(vTextInput);
return vTextInput;
}else if(type.equalsIgnoreCase("USState")){
Spinner vSpinnerInput = new Spinner(activity);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
activity,
android.R.layout.simple_spinner_item, USStates);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vSpinnerInput.setAdapter(dataAdapter);
recordItem.setEditView(vSpinnerInput);
return vSpinnerInput;
}else if(type.equalsIgnoreCase("keyword")){
Spinner vSpinnerInput = new Spinner(activity);
recordItem.setEditView(vSpinnerInput);
return vSpinnerInput;
}else if(type.equalsIgnoreCase("recordPicker")){
TextView textView = new TextView(activity);
textView.setTextSize(20);
textView.setGravity(Gravity.LEFT);
valueParms.topMargin = 17;
textView.setLayoutParams(valueParms);
//textView.setBackgroundColor(0xFFC2EAFF);
textView.setBackgroundColor(0xFFFFFFD0);
textView.setPadding(15, 7, 0, 7);
recordItem.setEditView(textView);
return textView;
}
Log.i("C2_UIHelper", "returned a null editView!");
return null;
}
public TextView buildLabelView(RecordItem recordItem){
TextView vLabel = new TextView(activity);
vLabel.setText(recordItem.getLabel());
vLabel.setTextSize(12);
vLabel.setLayoutParams(labelParms);
vLabel.setTextColor(0xFF777777);
return vLabel;
}
}