【发布时间】:2012-03-15 09:31:57
【问题描述】:
我在一个循环中有一个变量,每当我触摸一个按钮时我都会改变它。我需要在活动的最后使用这个变量来设置我的 viewflipper 显示哪个视图。整个事情的开始是因为我不断收到“在不同方法中定义的内部类中的非最终变量”错误。所以我在看这里并按照一些人的建议做了 - 制作一个本地最终变量,然后在 onTouch 方法中重新分配。见以下代码:
for(int categoryIndex = 0; categoryIndex <menuCategories.size(); categoryIndex++){
final CustomButton menuButton = new CustomButton(this);
menuButton.setId(ViewIdentification.getId());
menuButton.setText(menuCategories.get(categoryIndex).category_name);
menuButton.setTextColor(Color.argb(255, 77, 30, 16));
menuButton.setTextSize(35);
menuButton.setGravity(Gravity.CENTER);
menuButton.setTypeface(tf);
menuButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
menuButton.setPadding(10, 10, 10, 10);
sideMenu.addView(menuButton);
final int currentCategoryIndex = categoryIndex;
menuButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
myCurrentCategory = currentCategoryIndex;
Log.d("Touched Side Menu button ", menuButton.getId() + ": " + menuButton.getText().toString());
Log.d("My Current Category is ", Integer.valueOf(myCurrentCategory).toString());
return false;
}
});
........
.......
.......building more stuff within this loop
在这个循环中,我正在构建一个包含多个相对视图的线性视图数组(其中当然有任意数量的视图)。由于我拥有所有这些 LinearView,因此我创建了一个 viewflipper 来添加所有这些线性视图,然后取决于 myCurrentCategory 是什么,我将我的 Flipper 设置为。请参阅下面的代码:
ViewFlipper flipper = new ViewFlipper(this);
RelativeLayout.LayoutParams viewFlipperLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
viewFlipperLayoutParams.addRule(RelativeLayout.RIGHT_OF, sideMenu.getId());
viewFlipperLayoutParams.setMargins(0, 0, 100, 0);
//subMenuLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, screenLayout.getId());
flipper.setLayoutParams(viewFlipperLayoutParams);
for(int flipperIndex = 0; flipperIndex < subMenuLinearLayouts.size(); flipperIndex++){
flipper.addView(subMenuLinearLayouts.get(flipperIndex));
}
//set which part of the menu we want to see
flipper.setDisplayedChild(myCurrentCategory);
一个 subMenuLinearLayout 是一个具有相对布局的 LinearLayout,而这些相对布局具有其他视图(正如我之前解释的那样,但想清楚一点)。
请注意,我在程序顶部定义了 myCurrentCategory,因此它是全局定义的。当我将其设置为已知状态 0、1、2、3、4、5 时,ViewFlipper 正确地向我显示了正确的 LinearLayout ......所以我知道这是有效的。但是,在我根据 categoryIndex 为 myCurrentCategory 分配新值的 onTouch 方法中,ViewFlipper 不会翻转到该视图。我的日志语句表明有问题的 myCurrentCategory 变量甚至获得了正确的值。我刚刚测试过了。所以归结为为什么 ViewFlipper 没有“看到”变量的变化?谢谢!
【问题讨论】:
标签: android viewflipper touch-event