这是我在这里粘贴的示例代码。我真正想要的是在MainActivity中创建一个项目列表。我已经使用了GridView,因为很容易设置你想连续显示多少项。在它们之间创建间距也很容易。
我的目标是在GridView的Item中的ImageView中的Long Press位置打开一个ArcLayout。因此,我注册了OnTouchListener(以获取触摸位置)和OnLongClickListener(以便在长按时将ArcLayout定位到该位置)。
除了GridView中的第一项之外,这似乎适用于所有项目。出于某种原因,如果长按仅仅为GridView中的“第一项”,则不会调用LongClick方法。
这看起来很奇怪。我无法弄清楚“onTouch”为GridView中唯一的First Item消耗“ACTION_DOWN”事件的原因,而不是传递给“onLongClick方法”。
以下是示例应用的链接 Sample App
您可以在Log.d“Adapter”中看到,GridView中的第一个项目未检测到LongClick。
将OnTouchListener和OnLongClickListener注册到同一个视图会导致任何冲突吗?
MainActivity
public class MainActivity extends AppCompatActivity {
private GridView gridView;
private GridViewAdapter gridViewAdapter;
private ArrayList<Integer> lstIds;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.grid_view);
lstIds = new ArrayList<Integer>();
lstIds.add(R.drawable.img_burger);
lstIds.add(R.drawable.img_ham_burger);
lstIds.add(R.drawable.img_pancakes);
lstIds.add(R.drawable.img_pizza);
gridViewAdapter = new GridViewAdapter(this, lstIds);
gridView.setAdapter(gridViewAdapter);
}
}
GridView的BaseAdapter
// GridViewAdapter.java
public class GridViewAdapter extends BaseAdapter implements View.OnLongClickListener, View.OnTouchListener {
// Instance Variables
private final String TAG = "Adapter";
private Context context;
private ArrayList<Integer> lstImg;
private int resId;
// CONSTRUCTOR
public GridViewAdapter(Context context, ArrayList<Integer> lstImg) {
this.context = context;
this.lstImg = lstImg;
}
// Overridden Methods
@Override
public int getCount() {
return lstImg.size();
}
@Override
public Object getItem(int position) {
return lstImg.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_layout, parent, false);
}
ImageView imgItem = (ImageView) convertView.findViewById(R.id.img_view);
resId = lstImg.get(position);
imgItem.setImageResource(resId);
// Enabling the ImageView to be Long Clickable...
// imgItem.setLongClickable(true);
imgItem.setOnTouchListener(this);
imgItem.setOnLongClickListener(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 250);
convertView.setLayoutParams(params);
return convertView;
}
@Override
public boolean onLongClick(View v) {
Log.d(TAG, "onLongClick called...");
Toast.makeText(context, "Long Click!", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onTouch(View v, final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.d(TAG, "onTouch ACTION_DOWN event...");
}
return false;
}
}