在开发android程序时,遇到一个问题,ImageSwitcher只支持手动的切换图片,不支持自动定时的切换。因为xamarin的资料很少,官方也没有相应的教程,所以想到这个方法,利用job程序来实现后台的操作。
布局文件:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/relativeLayout1" android:background="#ffececec"> <ImageView android:src="@drawable/ImgSlideLeft" android:layout_width="50px" android:layout_height="wrap_content" android:id="@+id/btnFeatureLeft" android:layout_centerVertical="true" android:layout_alignParentLeft="true" /> <ImageSwitcher android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="638px" android:id="@+id/SwitcherProductFeature" android:layout_centerInParent="true" /> <ImageView android:src="@drawable/ImgSlideRight" android:layout_width="50px" android:layout_height="wrap_content" android:id="@+id/btnFeatureRight" android:layout_centerVertical="true" android:layout_alignParentRight="true" /> </RelativeLayout>
复制相应图片资源
后台代码:注意这里继承了GestureDetector.IOnGestureListener,监听用户的相关事件。代码中只写了 左滑和右滑事件。
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)] public class MainActivity : AppCompatActivity, ViewSwitcher.IViewFactory, GestureDetector.IOnGestureListener { private GestureDetector gestureDetector = null; private ImageSwitcher imageSwitcher; private int[] imgs = new int[]{ Resource.Drawable.p1, Resource.Drawable.p2, Resource.Drawable.p3, Resource.Drawable.p4, Resource.Drawable.p5, Resource.Drawable.p6 }; private int currentPosition; public TestJobService testjobservice; public TextView t1; Handler handler; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); //关键是这里,将MainActivity传给TestJobService类 handler = new Handler((Message msg) => { testjobservice = (TestJobService)msg.Obj; testjobservice.setUiCallback(this); }); SetContentView(Resource.Layout.activity_main); gestureDetector = new GestureDetector(this); imageSwitcher = FindViewById<ImageSwitcher>(Resource.Id.SwitcherProductFeature); currentPosition = 0; imageSwitcher.SetFactory(this); imageSwitcher.SetImageResource(Resource.Drawable.p1); t1 = FindViewById<TextView>(Resource.Id.tv1); Intent intent = new Intent(this, typeof(TestJobService)); intent.PutExtra("messenger", new Messenger(handler));//传参 StartService(intent); doService(); } public View MakeView() { ImageView img = new ImageView(this); img.SetBackgroundColor(Android.Graphics.Color.Transparent); img.SetScaleType(ImageView.ScaleType.FitCenter); return img; } public override bool OnTouchEvent(MotionEvent e) { return gestureDetector.OnTouchEvent(e); } public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e2.GetX() - e1.GetX() > 100) { currentPosition--; if (currentPosition < 0) currentPosition = imgs.Length - 1; //imageSwitcher.SetInAnimation(this, Android.Resource.Animation.FadeIn);//设置淡入动画 //imageSwitcher.SetInAnimation(this, Android.Resource.Animation.FadeOut); imageSwitcher.SetImageResource(imgs[currentPosition]); } else if (e2.GetX() - e1.GetX() < -100) { currentPosition++; if (currentPosition > imgs.Length - 1) currentPosition = 0; //imageSwitcher.SetInAnimation(this, Android.Resource.Animation.FadeIn);//设置淡入动画 //imageSwitcher.SetInAnimation(this, Android.Resource.Animation.FadeOut); imageSwitcher.SetImageResource(imgs[currentPosition]); } return true; } public bool OnDown(MotionEvent e) { return false; } public void OnLongPress(MotionEvent e) { } public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } public void OnShowPress(MotionEvent e) { } public bool OnSingleTapUp(MotionEvent e) { return false; } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } private void doService() { JobScheduler jobScheduler = (JobScheduler)GetSystemService(JobSchedulerService); ComponentName componentName = new ComponentName(this, Java.Lang.Class.FromType(typeof(TestJobService))); JobInfo jobinfo = new JobInfo.Builder(1001, componentName) .SetPeriodic(5000) //设置每5秒钟执行一次 .Build(); jobScheduler.Schedule(jobinfo); } //自动切换主要在这里实现。 public void OnReceivedStartJob() { currentPosition++; if (currentPosition > imgs.Length - 1) currentPosition = 0; imageSwitcher.SetImageResource(imgs[currentPosition]); } }
新建job处理类
[Service(Exported = true, Permission = "android.permission.BIND_JOB_SERVICE")] public class TestJobService : JobService { public int i = 0; MainActivity owner; public override bool OnStartJob(JobParameters args) { doJob (args); return false; } public override bool OnStopJob(JobParameters args) { Log.Info("服务停止", "stop job service"); return true; } private void doJob(JobParameters args) { if (args.JobId == 1001) { owner.OnReceivedStartJob();//返回到主线程中操作。 } else if(args.JobId==1002) { //这里可以扩展第二个或第三个,根据jobiD判断 } } public void setUiCallback(MainActivity activity) { owner = activity; } public override StartCommandResult OnStartCommand(Intent intent, Android.App.StartCommandFlags flags, int startId) { var callback = (Messenger)intent.GetParcelableExtra("messenger"); var m = Message.Obtain(); m.What = 2;//如果有多种消息,可以通过这个参数进行判断,进行不同的操作 m.Obj = this; try { callback.Send(m); } catch (RemoteException e) { Log.Error("Tag", e, "Error passing service object back to activity."); } return StartCommandResult.NotSticky; } }
运行效果图
我还添加了左右两个按钮,也可以添加事件,点击切换。
官方关于Android 作业计划程序的介绍请参考以下链接。
https://learn.microsoft.com/zh-cn/xamarin/android/platform/android-job-scheduler