减少视图上的强制转换量

时间:2013-06-29 05:18:42

标签: android

我似乎无法弄清楚如何更有效地编写此代码。我正在迭代视图以检查有效性(输入的文本),但我发现自己投入太多了。根据eclipse我需要强制转换才能访问视图上的方法。这是代码:

// Verify Drivers/Vehicles Entered
private boolean checkDriversVehiclesValidity() {
    int viewCount = mContainerView.getChildCount();
    for (int i = 0; i < viewCount; i++) {
        View v = mContainerView.getChildAt(i);
        if (v.getId() == R.id.driverVehicleRow) {
            for (int j = 0; j < ((LinearLayout) v).getChildCount(); j++) {
                View v1 = ((ViewGroup) v).getChildAt(j);
                if (v1 instanceof CustomAutoCompleteTextView) {
                    if (((CustomAutoCompleteTextView) v1).getError() != null) {
                        v1.requestFocus();
                        return false;
                    }
                    if (v1.getId() == R.id.drivers_field) {
                        String driverNumber = ((CustomAutoCompleteTextView) v1).getText().toString();
                        if ("".equals(driverNumber)) {
                            ((CustomAutoCompleteTextView) v1).setError("Driver required");
                            v1.requestFocus();
                            return false;
                        }
                    } else if (v1.getId() == R.id.vehicles_field) {
                        String vehicleNumber = ((CustomAutoCompleteTextView) v1).getText().toString();
                        if ("".equals(vehicleNumber)) {
                            ((CustomAutoCompleteTextView) v1).setError("Vehicle required");
                            v1.requestFocus();
                            return false;
                        }
                    }
                }
            }
        }
    }
    return true;
}

1 个答案:

答案 0 :(得分:1)

例如,在检查

之后
if (v1 instanceof CustomAutoCompleteTextView)

您可以确定它是CustomAutoCompleteTextView的实例,因此您可以将其分配给正确类型的变量,如下所示:

CustomAutoCompleteTextView cv =(CustomAutoCompleteTextView)v1;

并稍后使用cv代替((CustomAutoCompleteTextView) v1)