我正在尝试在复合组件中存在的gridview中更新图像按钮。我尝试了几种不同的方法,但不知怎的,我不能让我工作。这是我的代码:
这是一个合并了xml-layout的类:
public class DialPadView extends RelativeLayout {
private GridView gv;
public DialPadView(Context context, AttributeSet attr) {
super(context, attr);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.dialpad, this, true);
gv = (GridView)findViewById(R.id.gv_dials);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
TableLayout tl = (TableLayout)findViewById(R.id.tl_main);
int leftHeight = this.getHeight() - tl.getHeight();
gv.setAdapter(new DialpadAdapter(this.getContext(), leftHeight));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
DialpadAdapters getView方法如下所示:
public View getView(int position, View convertView, ViewGroup parent) {
DialButton imgBtn;
if(convertView == null) {
imgBtn = new DialButton(mContext);
imgBtn.setLayoutParams(new GridView.LayoutParams(btnHeight, btnHeight));
imgBtn.setScaleType(DialButton.ScaleType.FIT_CENTER);
imgBtn.setPadding(2, 2, 2, 2);
} else {
imgBtn = (DialButton) convertView;
}
imgBtn.setImageResource(mDigitsId[position]);
imgBtn.setBackgroundColor(color.transparent);
imgBtn.setPosition(position);
imgBtn.setHapticFeedbackEnabled(true);
imgBtn.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
DialButton ib = (DialButton) v;
if(event.getAction() == MotionEvent.ACTION_DOWN) {
ib.changeImage(mDigitsOverId[ib.getPosition()]);
ib.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
Log.d("BUTTON PRESSED", "THIS BUTTON IS INDEED PRESSED!");
} else {
ib.changeImage(mDigitsId[ib.getPosition()]);
}
return false;
}
});
return imgBtn;
}
最后我的DialButton只是一个扩展的ImageButton:
public class DialButton extends ImageButton {
private int _position;
public DialButton(Context ctx) {
super(ctx);
}
public void changeImage(int resource_id) {
this.invalidate();
this.setImageResource(resource_id);
this.invalidate();
}
public void setPosition(int pos) {
_position = pos;
}
public int getPosition() {
return _position;
}
}
getView方法中的日志消息打印,所以我知道getView被调用但不知何故图像不会改变。请问任何人都能看出我做错了什么吗?
编辑:为了澄清,我已经尝试直接传递资源ID。
答案 0 :(得分:1)
您可以尝试使用notifyDataSetChanged()作为DialpadAdapter适配器。它应该刷新附加的网格或图库视图。
答案 1 :(得分:0)
首先,我怀疑在设置新图片之前,您需要先调用this.invalidate()
。
另外,我会尝试这样做:
final DialButton imgBtn;
...
imgBtn.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN ||
event.getAction() == MotionEvent.ACTION_MOVE) {
imgBtn.changeImage(mDigitsOverId[ib.getPosition()]);
imgBtn.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
Log.d("BUTTON PRESSED", "THIS BUTTON IS INDEED PRESSED!");
} else {
imgBtn.changeImage(mDigitsId[ib.getPosition()]);
}
return false;
}
});
由于触摸屏很敏感且手指总是至少移动一点,因此ACTION_MOVING往往是在触摸输入期间不断调用的那个。