Android Studio中如何用循环替代重复嵌套的条件判断代码?
用循环替代嵌套if优化代码
当然可以用循环替代这种嵌套if的重复代码,而且能大幅提升代码的可读性和可维护性。
原代码逻辑分析
你的代码逻辑是:当otterPurchased >= n(n从1到10)时,依次显示layoutOtter(n+1)对应的TableRow控件。本质是根据otterPurchased的值,显示前otterPurchased个目标控件(最多10个)。
优化方案1:提前定义ID数组(推荐)
这种方式性能更高,直接使用预定义的资源ID,避免反射操作:
// 定义目标控件的ID数组,顺序对应要显示的先后顺序 int[] otterLayoutIds = { R.id.layoutOtter2, R.id.layoutOtter3, R.id.layoutOtter4, R.id.layoutOtter5, R.id.layoutOtter6, R.id.layoutOtter7, R.id.layoutOtter8, R.id.layoutOtter9, R.id.layoutOtter10, R.id.layoutOtter11 }; // 计算需要显示的控件数量,不超过数组长度 int displayCount = Math.min(otterPurchased, otterLayoutIds.length); for (int i = 0; i < displayCount; i++) { TableRow tableRow = findViewById(otterLayoutIds[i]); if (tableRow != null) { tableRow.setVisibility(View.VISIBLE); } }
优化方案2:动态获取资源ID(灵活但性能稍差)
如果控件命名有规律(比如layoutOtter2到layoutOtter11),可以通过getResources().getIdentifier()动态获取ID,适合控件数量可能变化的场景:
// 最多显示到第10个控件(对应layoutOtter11) int maxDisplay = Math.min(otterPurchased, 10); for (int i = 1; i <= maxDisplay; i++) { String idName = "layoutOtter" + (i + 1); int resId = getResources().getIdentifier(idName, "id", getPackageName()); if (resId != 0) { TableRow tableRow = findViewById(resId); if (tableRow != null) { tableRow.setVisibility(View.VISIBLE); } } }
进一步优化:缓存控件实例
因为你的代码处于永久循环中,重复调用findViewById会消耗性能。建议提前缓存控件实例,后续循环直接操作:
// 类成员变量 private TableRow[] otterTableRows; // 在初始化方法(如onCreate)中缓存控件 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); otterTableRows = new TableRow[] { findViewById(R.id.layoutOtter2), findViewById(R.id.layoutOtter3), findViewById(R.id.layoutOtter4), findViewById(R.id.layoutOtter5), findViewById(R.id.layoutOtter6), findViewById(R.id.layoutOtter7), findViewById(R.id.layoutOtter8), findViewById(R.id.layoutOtter9), findViewById(R.id.layoutOtter10), findViewById(R.id.layoutOtter11) }; } // 永久循环中的代码 int displayCount = Math.min(otterPurchased, otterTableRows.length); for (int i = 0; i < displayCount; i++) { if (otterTableRows[i] != null) { otterTableRows[i].setVisibility(View.VISIBLE); } }
内容的提问来源于stack exchange,提问作者Rose
相关产品推荐
相关产品推荐

