EditText&在swipegesture中的ImageButton

时间:2016-07-17 13:02:13

标签: android xamarin xamarin.android

我目前有一个包含多个编辑文字的大型活动&图像按钮。 但是,当我为导航添加滑动手势时,所有小部件都不会引发任何点击...

有人已经面临这个问题并有解决方案吗?

感谢。

编辑添加代码源:

这是带有表单的线性布局,视图非常大,所以我只是将代码发布到第一个edittext。

<!-- Form -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="100">
      <Space
          android:layout_width="match_parent"
          android:layout_weight="2"
          android:layout_height="0dp" />
      <!--Title-->
      <LinearLayout
          android:layout_height="0dp"
          android:layout_weight="10"
          android:layout_width="match_parent"
          android:orientation="horizontal"
          android:weightSum="100">
        <Space
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="match_parent" />
        <Cheer_up_app.Droid.Model.Custom.FontTextView
            android:textColor="@color/white"
            customFont:customFont="Fonts/CarterOne.ttf"
            android:text="@string/title"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:gravity="center_vertical|right"
            android:layout_weight="25" />
        <Space
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="match_parent" />
        <EditText
            android:singleLine="true"
            android:layout_width="0dp"
            android:layout_weight="70"
            android:layout_height="wrap_content"
            android:id="@+id/newchallenge_title"
            android:background="@drawable/border_all"
            android:paddingRight="5dp"
            android:paddingLeft="5dp"
            android:layout_gravity="center_vertical" />
        <Space
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="match_parent" />
</LinearLayout>
<!-- ect...-->
</LinearLayout>

这是我的活动,我没有删除代码,因为我不知道我写的东西是否可以处理这个错误。

namespace Cheer_up_app.Droid.Model
{
    [Activity(Label = "NewChallengeActivity", ScreenOrientation = ScreenOrientation.Portrait, WindowSoftInputMode = SoftInput.AdjustPan)]
    public class NewChallengeActivity : Activity, GestureDetector.IOnGestureListener
    {
        TextView pictureName;
        private Challenge currentChallenge;
        private List<string> hoursList;
        private List<string> daysList;
        private List<Cheer_up_app.Model.Type> challengeType;
        private ChallengeC commonChallenge;
        private int initialSpinnerH;
        private int initialSpinnerD;
        private TimeSpan selectedTimespan;
        private Bitmap helpImage;
        private string type;

        #region gesture declaration
        private GestureDetector _gestureDetector;
        private const int SWIPE_MIN_DISTANCE = 120;
        private const int SWIPE_MAX_OFF_PATH = 250;
        private const int SWIPE_THRESHOLD_VELOCITY = 200;
        #endregion

        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);


            this.SetContentView(Resource.Layout.NewChallengeView);
            await InitChallenge();

            InitView();

            _gestureDetector = new GestureDetector(this);

        }

        /// <summary>
        /// init challenge object
        /// </summary>
        private async Task InitChallenge()
        {
            FindViewById<LinearLayout>(Resource.Id.newChallenge_progress_layout).Visibility = ViewStates.Visible;

            currentChallenge = new Challenge();
            commonChallenge = new ChallengeC();
            currentChallenge.Difficulty = CommonResources.Easy;
            currentChallenge.UserId = User.Instance.Id;

            challengeType = await commonChallenge.GetListType();
            TranslateType();
            currentChallenge.ChallengeTypeId = challengeType.FirstOrDefault(ct => ct.TypeName == CommonResources.Question).Id;
            FindViewById<LinearLayout>(Resource.Id.newChallenge_progress_layout).Visibility = ViewStates.Gone;

        }

        /// <summary>
        /// Init view 
        /// </summary>
        private void InitView()
        {



            // buttons type
            var buttonQuestion = FindViewById<ImageButton>(Resource.Id.typeQuestion);
            var buttonPhoto = FindViewById<ImageButton>(Resource.Id.typePhoto);
            var buttonVideo = FindViewById<ImageButton>(Resource.Id.typeVideo);


            // buttons level
            var buttonEasy = FindViewById<ImageButton>(Resource.Id.levelEasy);
            var buttonMed = FindViewById<ImageButton>(Resource.Id.levelMed);
            var buttonHard = FindViewById<ImageButton>(Resource.Id.levelHard);

            buttonEasy.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Easy_act), "drawable", PackageName));
            buttonMed.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Medium_des), "drawable", PackageName));
            buttonHard.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Hard_des), "drawable", PackageName));


            // button add photo
            var buttonAdd = FindViewById<ImageButton>(Resource.Id.addPhoto);

            // button next
            var buttonNext = FindViewById<ImageButton>(Resource.Id.imageButtonNext);
            buttonNext.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Next), "drawable", PackageName));


            // button back
            var buttonBack = FindViewById<ImageButton>(Resource.Id.buttonReturnNewChallenge);
            buttonBack.Click += delegate
            {
                OnBackPressed();
            };

            // set one choice for type
            buttonQuestion.Click += delegate
            {
                buttonQuestion.SetImageResource(Resource.Drawable.button_question_enable);
                buttonPhoto.SetImageResource(Resource.Drawable.button_photo_disable);
                buttonVideo.SetImageResource(Resource.Drawable.button_video_disable);
                currentChallenge.ChallengeTypeId = challengeType.FirstOrDefault(ct => ct.TypeName == CommonResources.Question).Id;
                type = CommonResources.Question;

            };
            buttonPhoto.Click += delegate
            {
                buttonPhoto.SetImageResource(Resource.Drawable.button_photo_enable);
                buttonQuestion.SetImageResource(Resource.Drawable.button_question_disable);
                buttonVideo.SetImageResource(Resource.Drawable.button_video_disable);
                currentChallenge.ChallengeTypeId = challengeType.FirstOrDefault(ct => ct.TypeName == CommonResources.Photo).Id;
                type = CommonResources.Photo;

            };
            buttonVideo.Click += delegate
            {
                buttonVideo.SetImageResource(Resource.Drawable.button_video_enable);
                buttonQuestion.SetImageResource(Resource.Drawable.button_question_disable);
                buttonPhoto.SetImageResource(Resource.Drawable.button_photo_disable);
                currentChallenge.ChallengeTypeId = challengeType.FirstOrDefault(ct => ct.TypeName == CommonResources.Video).Id;
                type = CommonResources.Video;

            };

            // set one choice for level
            buttonEasy.Click += delegate
            {
                buttonEasy.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Easy_act), "drawable", PackageName));
                buttonMed.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Medium_des), "drawable", PackageName));
                buttonHard.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Hard_des), "drawable", PackageName));
                currentChallenge.Difficulty = CommonResources.Easy;
            };
            buttonMed.Click += delegate
            {
                buttonEasy.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Easy_des), "drawable", PackageName));
                buttonMed.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Medium_act), "drawable", PackageName));
                buttonHard.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Hard_des), "drawable", PackageName));
                currentChallenge.Difficulty = CommonResources.Medium;

            };
            buttonHard.Click += delegate
            {
                buttonEasy.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Easy_des), "drawable", PackageName));
                buttonMed.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Medium_des), "drawable", PackageName));
                buttonHard.SetImageResource(Resources.GetIdentifier(Resources.GetString(Resource.String.Hard_act), "drawable", PackageName));
                currentChallenge.Difficulty = CommonResources.Hard;

            };

            // choice photo

            pictureName = FindViewById<TextView>(Resource.Id.pictureName);
            pictureName.Visibility = ViewStates.Invisible;

            buttonAdd.Click += delegate
            {
                var imageIntent = new Intent();
                imageIntent.SetType("image/*");
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photo"), 0);
            };


            hoursList = ChallengeFormData.Hours();
            daysList = ChallengeFormData.Days();
            PrepareSpinnersData();
            //prepare spinner
            Spinner spinnerD = (Spinner)FindViewById<Spinner>(Resource.Id.spinnerDay);
            ArrayAdapter adapter = new SpinnerAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, daysList);
            spinnerD.Adapter = adapter;

            Spinner spinnerH = (Spinner)FindViewById<Spinner>(Resource.Id.spinnerHour);
            adapter = new SpinnerAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, hoursList);
            spinnerH.Adapter = adapter;

            initialSpinnerH = spinnerH.SelectedItemPosition;
            initialSpinnerD = spinnerD.SelectedItemPosition;
            //event for spinnners
            spinnerH.ItemSelected += (sender, args) =>
            {
                if (args.Position != initialSpinnerH)
                {
                    spinnerD.SetSelection(0);
                    string selectedHour = spinnerH.SelectedItem.ToString().Split(' ')[0];
                    string hour = string.Empty;
                    if (selectedHour.Length == 3)
                    {
                        hour = selectedHour[0] + "" + selectedHour[1] + ":00";

                    }
                    else
                    {
                        hour = selectedHour[0] + ":00";
                    }
                    TimeSpan.TryParse(hour, out selectedTimespan);
                }
            };

            //event for spinnners
            spinnerD.ItemSelected += (sender, args) =>
            {
                if (args.Position != initialSpinnerH)
                {
                    spinnerH.SetSelection(0);
                    string day = spinnerD.SelectedItem.ToString().Split(' ')[0];
                    TimeSpan.TryParse(day, out selectedTimespan);

                }
            };

        }

        /// <summary>
        /// Traduce typename in each type
        /// </summary>
        /// <param name="types">Type list</param>
        private void TranslateType()
        {
            List<string> typeList = new List<string>();
            foreach (var type in challengeType)
            {
                int resource = Resources.GetIdentifier(type.TypeName, "string", PackageName);
                type.TranslatedTypeName = Resources.GetString(resource);
            }
        }

        /// <summary>
        /// Prepare spinners data adding correct day or hour word
        /// </summary>
        private void PrepareSpinnersData()
        {
            string days = Resources.GetString(Resource.String.days);
            string hours = Resources.GetString(Resource.String.hours);
            hoursList.Insert(0, Resources.GetString(Resource.String.chooseDuration));
            daysList.Insert(0, Resources.GetString(Resource.String.chooseDuration));

            for (var i=1;i<hoursList.Count; i++)
            {
                hoursList[i] = string.Format("{0} {1}", hoursList[i], hours);
            }

            for (var i = 1; i < daysList.Count; i++)
            {
                daysList[i] = string.Format("{0} {1}", daysList[i], days);
            }
        }

        /// <summary>
        /// Navigate to OnBackPressed
        /// </summary>
        public override void OnBackPressed()
        {
            base.OnBackPressed();
            this.OverridePendingTransition(Resource.Animation.LeftToRightIn, Resource.Animation.LeftToRightOut);
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {
                pictureName.Visibility = ViewStates.Visible;
                pictureName.Text = data.Data.LastPathSegment;
                helpImage = MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
            }
        }

        /// <summary>
        /// Button next, go to friend list
        /// </summary>
        /// <param name="v"></param>
        [Java.Interop.Export("BtnNextChallenge")]
        public void BtnNextChallenge(View v)
        {
            currentChallenge.Title = FindViewById<EditText>(Resource.Id.newchallenge_title).Text;
            currentChallenge.Description = FindViewById<EditText>(Resource.Id.newchallenge_description).Text;

            if (!IsValidated())
            {
                //user already registered, display error message
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle(GetString(Resource.String.emptyAnswer));
                alert.SetMessage(GetString(Resource.String.emptyAnswerText));
                //run the alert in UI thread to display in the screen
                RunOnUiThread(() => {
                    alert.Show();
                });
                return;
            }

            currentChallenge.ValidityPeriod = selectedTimespan;
            currentChallenge.Points = commonChallenge.CalculPoints(type, currentChallenge.Difficulty);


            Intent activity = new Intent(this, typeof(FriendListActivity));
            activity.PutExtra("NewChallenge", Challenge.ConvertToJson(currentChallenge));
            if(helpImage != null)
            {
                byte[] bitmapData;
                using (var stream = new MemoryStream())
                {
                    helpImage.Compress(Bitmap.CompressFormat.Png, 0, stream);
                    bitmapData = stream.ToArray();
                }
                activity.PutExtra("byteArray", bitmapData);
            }


            StartActivity(activity);
            Finish();
        }

        /// <summary>
        /// Check if challenge is validated
        /// </summary>
        /// <returns>boolean</returns>
        private bool IsValidated()
        {
            if(currentChallenge.ChallengeTypeId != 0 && !string.IsNullOrEmpty(currentChallenge.Description) && !string.IsNullOrEmpty(currentChallenge.Difficulty) && !string.IsNullOrEmpty(currentChallenge.Title) && !string.IsNullOrEmpty(currentChallenge.UserId) && selectedTimespan != null)
            {
                return true;
            }

            return false;
        }

        #region GestureDetector.IOnGestureListener methods
        public bool OnDown(MotionEvent e)
        {
            return false;
        }

        public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
        {
            try
            {
                if (System.Math.Abs(e1.GetY() - e2.GetY()) > SWIPE_MAX_OFF_PATH)
                {
                    return false;
                }

                // right to right swipe
                if (e2.GetX() - e1.GetX() > SWIPE_MIN_DISTANCE && System.Math.Abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
                {
                    OnBackPressed();
                }
            }
            catch (System.Exception e)
            {
                Log.Debug("gesture", e.Message);
            }
            return true;
        }

        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 bool DispatchTouchEvent(MotionEvent e)
        {
            _gestureDetector.OnTouchEvent(e);
            return false;
        }

        #endregion
    }
}

1 个答案:

答案 0 :(得分:1)

你压倒DispatchTouchEvent&amp;它不会将事件分派给窗口元素,因为它不会调用它的基本DispatchTouchEvent构造函数。尝试

public override bool DispatchTouchEvent(MotionEvent ev)
{
   _gestureDetector.OnTouchEvent(ev);
   return base.DispatchTouchEvent(ev);
}