在我的xamarin Android项目的微调器中,我想将clickable设置为false,但仍然通过OnTouchListener检测点击次数。这样我就可以抑制出现的项目列表,除非用户点击微调器视图的特定部分。 这种方法在KitKat和更低版本中完美运行,但在Lollipop和更高版本中,可点击设置似乎没有效果,并且微调器总是在单击时显示项目列表。 有没有人知道我如何在Lollipop中获得一个微调器,之后在点击时不显示项目列表但仍然响应点击事件?
以下是我的测试项目中的代码。
布局xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Spinner android:id="@+id/testSpinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom ="10sp"/>
</LinearLayout>
活动代码:
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Spinner spinner = FindViewById<Spinner>(Resource.Id.testSpinner);
List<string> items = new List<string>() { "Dave", "Ben", "Dan" };
spinner.Clickable = false;
ConnectArrayAdapter adapter = new ConnectArrayAdapter(this, spinner, items);
spinner.Adapter = adapter;
}
}
来自阵列适配器的相关代码位(我只希望在用户点击视图中的图像时显示这些项目):
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = base.GetView(position, convertView, parent);
TextView textView = (TextView)view;
textView.SetTextColor(Android.Graphics.Color.Black);
textView.SetTextSize(Android.Util.ComplexUnitType.Dip, 16);
textView.Gravity = TextGravity;
textView.SetCompoundDrawablesWithIntrinsicBounds(null, null, m_image, null);
textView.SetOnTouchListener(new SelectImageTouchListener(textView, m_parent));
m_parent.Clickable = false;
return view;
}
private class SelectImageTouchListener : RightDrawableOnTouchListener
{
private Spinner m_spinner;
public SelectImageTouchListener(TextView view, Spinner spinner) : base(view)
{
m_spinner = spinner;
}
public override bool OnDrawableTouch(MotionEvent e)
{
m_spinner.PerformClick();
e.Action = MotionEventActions.Cancel;
return false;
}
}
public abstract class RightDrawableOnTouchListener : Java.Lang.Object, View.IOnTouchListener
{
private Drawable m_drawable;
private int m_fuzz = 10;
public RightDrawableOnTouchListener(TextView view) : base()
{
List<Drawable> drawables = view.GetCompoundDrawables().ToList();
if (drawables != null && drawables.Count == 4)
m_drawable = drawables[2];
}
public new IntPtr Handle
{
get
{
return base.Handle;
}
}
public new void Dispose()
{
base.Dispose();
}
public bool OnTouch(View v, MotionEvent e)
{
if (e.Action == MotionEventActions.Down && m_drawable != null)
{
int x = (int)e.GetX();
int y = (int)e.GetY();
Rect bounds = m_drawable.Bounds;
if (x >= (v.Right - bounds.Width() - m_fuzz) && x <= (v.Right - v.PaddingRight + m_fuzz)
&& y >= (v.PaddingTop - m_fuzz) && y <= (v.Height - v.PaddingBottom) + m_fuzz)
{
return OnDrawableTouch(e);
}
}
return false;
}
public abstract bool OnDrawableTouch(MotionEvent e);
}