我有ImageView
。我需要对ImageView使用onLongClickListener
。当我使用这段代码时,没有任何事情发生。
代码:
gallery=(Gallery)findViewById(R.id.gall1);
gallery.setAdapter(new ImageAdapter(MainActivity.this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(
AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
final ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
imageView.setLongClickable(true);
imageView.setOnLongClickListener(new View.OnLongClickListener(){
@Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Long Press work", Toast.LENGTH_SHORT).show();
return true;
}
});
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v,MotionEvent event) {
// TODO Auto-generated method stub
layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN :
{
parms = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
dx = event.getRawX() - parms.leftMargin;
dy = event.getRawY() - parms.topMargin;
}
break;
case MotionEvent.ACTION_MOVE :
{
x = event.getRawX();
y = event.getRawY();
parms.leftMargin = (int) (x-dx);
parms.topMargin = (int) (y - dy);
imageView.setLayoutParams(parms);
}
break;
case MotionEvent.ACTION_UP :
{
}
break;
}
return true;
}
});
}
});
答案 0 :(得分:14)
您需要按代码启用长按:
imageView.setLongClickable(true);
imageView.setClickable(true);
最后一行可能没有必要,但也没有任何麻烦。
答案 1 :(得分:8)
没有必要在代码中执行setLongClickable,在XML中定义它时更好
android:longClickable="true"