此代码以编程方式生成一个布局,该布局以数组中定义的方式由视图和 TextViews 组成。但是,我正在尝试使每个 TextView 都可点击,从而显示对该 TextView 更大解释的祝酒词。由于 toast 需要特定于特定的 TextView ,我试图在位置 i 使用另一个解释数组来设置 TextView 。但是,当我尝试执行此操作时,我收到错误“无法引用以不同方法定义的内部类中的非最终变量”。
所以我想知道,我该如何解决这个问题?i
不能是最终的,因为它在每次循环迭代中都会发生变化?
for ( int i = 0; i < formulae.length; i++){
if (formulae[i].equals("horizontalrule")){
View rule = new View(FormulaeActivity.this);
rule.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 2));
rule.setBackgroundColor(0xFF000000);
View spacerbig = new View(FormulaeActivity.this);
spacerbig.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 20));
spacerbig.setBackgroundResource(android.R.color.transparent);
container.addView(rule);
container.addView(spacerbig);
}
else{
View spacersmall1 = new View(FormulaeActivity.this);
spacersmall1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 5));
spacersmall1.setBackgroundResource(android.R.color.transparent);
tx[i] = new TextView(FormulaeActivity.this);
tx[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 50));
tx[i].setText(Html.fromHtml(formulae[i]));
tx[i].setTextSize(20);
tx[i].setPadding(10, 0, 0, 0);
tx[1].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), Html.fromHtml(explanations[i]), Toast.LENGTH_SHORT).show();
// ^this is the offending line
}
});
container.addView(tx[i]);
container.addView(spacersmall1);
}