我正在使用自定義網格適配器創建圖像按鈕並在活動上顯示它們,使用方法SetImageResource()
設置按鈕的src圖像。Android(Xamarin)selectableItemBackground - SetBackgroundResource不與SetImageResource配合使用
然而,當點擊這些按鈕沒有所需的按鈕點擊/連鎖反應。環顧四周後,我發現一對夫婦爲解決方案,利用TypedValue
與SetBackgroundResource()
,或利用與SetBackgroundDrawable()
一個TypedArray
。如果沒有圖像資源,這些方法都可以使用,但是在添加圖像資源後,selectableItemBackground
效果消失。
的代碼如下:
ImageButton button;
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
// Grid buttons
convertView = inflater.Inflate(Resource.Layout.sublayout_Menu_Button, null);
button = convertView.FindViewById<ImageButton>(Resource.Id.mainMenu_ImgBtn);
button.SetMinimumHeight(Main_Menu.GRID_HEIGHT/numRows);
TypedValue tv = new TypedValue();
context.Theme.ResolveAttribute(Resource.Attribute.selectableItemBackground, tv, true);
button.SetBackgroundResource(tv.ResourceId);
// This code is another method that works similarly to the above
//int[] attrs = new int[] { Android.Resource.Attribute.SelectableItemBackground };
//TypedArray ta = context.ObtainStyledAttributes(attrs);
//Drawable drawableFromTheme = ta.GetDrawable(0);
//ta.Recycle();
//button.SetBackgroundDrawable(drawableFromTheme);
button.SetImageResource(buttonImages[position]);
switch (position)
{
case 0:
button.Click += delegate
{
Intent intent = new Intent(context, typeof(Select_Hospital));
context.StartActivity(intent);
};
break;
case 1:
button.Click += delegate
{
Intent intent = new Intent(context, typeof(My_Appointments));
context.StartActivity(intent);
};
break;
case 2:
button.Click += delegate
{
Intent intent = new Intent(context, typeof(Treatment_Information));
context.StartActivity(intent);
};
break;
case 3:
button.Click += delegate
{
Intent intent = new Intent(context, typeof(Search));
context.StartActivity(intent);
};
break;
}
}
我怎樣才能解決這個問題呢?任何幫助將非常感謝!
- 編輯 -
MyImageButton代碼:
class MyImageButton : ImageButton, IOnTouchListener
{
private Context context;
public MyImageButton(Context context, IAttributeSet attrs) : base(context, attrs)
{
this.context = context;
this.SetOnTouchListener(this);
}
public bool OnTouch(View v, MotionEvent e)
{
if (e.Action == MotionEventActions.Down)
{
ImageView iv = (ImageView)v;
iv.SetColorFilter(new Android.Graphics.Color(context.GetColor(Resource.Color._5_grey)));
}
else if (e.Action == MotionEventActions.Up)
{
ImageView iv = (ImageView)v;
iv.ClearColorFilter();
}
return true;
}
};
AXML:
<?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">
<Dental_IT.Droid.Adapters.MyImageButton
android:id="@+id/mainMenu_ImgBtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:background="@null" />
</LinearLayout>
@Ryalis,這可以解決您的問題? –
動畫確實有效,但單擊委託事件現在不起作用 – Ryalis
@Ryalis,當我可以使用我的電腦時,我會更新我的答案。 –