0

У меня есть ListView, в который будут загружаться данные из БД (но пока опустим это, сейчас будет просто два массива). Мне нужно написать адаптер, который примет 2 массива, обработает их, а в конце выдаст таблицу, с которой можно работать. Заполнение должно происходить с каким-нибудь ускорителем типа ViewHolder, будут тысячи элементов заполняться. При этом каждая View (под View я подразумеваю все текстовые поля в LinearLayout разметке) должна:

  1. Менять свой цвет на серый, когда на нее нажали, тем самым создавая эффект нажатия.
  2. После трех секунд удержания, вызывать контекстное меню и передавать в него значения текстовых полей (для дальнейшей работы с БД).
  3. Если нажать на View и сдвинуть его на 30 пикселей по оси Y — нажатие должно "слетать", а передвижение ListView продолжаться (с этим у меня и возникли проблемы).

Вот две разметки под два разных массива:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
    android:id="@+id/linearLayout_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/black" >

    <TextView
        android:id="@+id/text_1"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:layout_marginBottom="0.5dp" />

    <TextView
        android:id="@+id/text_2"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="46"
        android:layout_marginLeft="0.5dp"
        android:layout_marginBottom="0.5dp" />

    <TextView
        android:id="@+id/text_3"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="46"
        android:layout_marginLeft="0.5dp"
        android:layout_marginBottom="0.5dp" />

</LinearLayout>


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout_2"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/black" >

    <TextView
        android:id="@+id/text_1"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="8"
        android:layout_marginLeft="1dp"
        android:layout_marginBottom="1dp" />

    <TextView
        android:id="@+id/text_2"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="23"
        android:layout_marginLeft="1dp"
        android:layout_marginBottom="1dp" />

    <TextView
        android:id="@+id/text_3"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="23"
        android:layout_marginLeft="1dp"
        android:layout_marginBottom="1dp" />

    <TextView
        android:id="@+id/text_4"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="23"
        android:layout_marginLeft="1dp"
        android:layout_marginBottom="1dp" />

    <TextView
        android:id="@+id/text_5"
        android:background="@color/white"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="23"
        android:layout_marginLeft="1dp"
        android:layout_marginRight="1dp"
        android:layout_marginBottom="1dp" />
</LinearLayout>

Список должен выглядеть примерно вот так (элементы просто заполнены массивами, созданными в цикле):

введите сюда описание изображения

Как можно это написать (подскажите готовый алгоритм или у кого-то может есть такой же, или кто-то вообще его напишет :D)?


Вот адаптер, который я написал, но, по всей видимости, его нужно переписывать, потому что он не работает, как нужно:

public class CustomListAdapter_Words extends BaseAdapter {

        private final String TAG = "myApplication";
        private final String MSG = "Adapter: ";
        private final int FIRST_WORDS = 0;
        private final int SECOND_WORDS = 1;
        private final int FIRST_ARRAY_LENGTH;

        private final Activity mContext;
        private final String[][] mWordsForm1;
        private final String[][] mWordsForm2;
        private LayoutInflater mInflater;
        private float HEIGHT = 100;

        private static HoldTimer timer;

        public CustomListAdapter_Words(Activity context, String[][] wordsForm1, String[][] wordsForm2) {

            mContext = context;
            mWordsForm1 = wordsForm1;
            mWordsForm2 = wordsForm2;
            mInflater = context.getLayoutInflater();
            FIRST_ARRAY_LENGTH = mWordsForm1.length;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;
            int type = getItemViewType(position);

            if (convertView == null) {
                holder = new ViewHolder();

                switch (type) {
                    case FIRST_WORDS:
                        convertView = mInflater.inflate(R.layout.row_words_form_1, null, true);

                        holder.textView1Form1 = (TextView) convertView.findViewById(R.id.text_1);
                        holder.textView2Form1 = (TextView) convertView.findViewById(R.id.text_2);
                        holder.textView3Form1 = (TextView) convertView.findViewById(R.id.text_3);

                        holder.linearLayout_1 = (LinearLayout) convertView.findViewById(R.id.linearLayout_1);
                        break;
                    case SECOND_WORDS:
                        convertView = mInflater.inflate(R.layout.row_words_form_2, null, true);

                        holder.textView1Form2 = (TextView) convertView.findViewById(R.id.text_1);
                        holder.textView2Form2 = (TextView) convertView.findViewById(R.id.text_2);
                        holder.textView3Form2 = (TextView) convertView.findViewById(R.id.text_3);
                        holder.textView4Form2 = (TextView) convertView.findViewById(R.id.text_4);
                        holder.textView5Form2 = (TextView) convertView.findViewById(R.id.text_5);

                        holder.linearLayout_2 = (LinearLayout) convertView.findViewById(R.id.linearLayout_2);
                        break;
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            switch (type) {
                case FIRST_WORDS:
                    holder.textView1Form1.setText(mWordsForm1[position][0]);
                    holder.textView2Form1.setText(mWordsForm1[position][1]);
                    holder.textView3Form1.setText(mWordsForm1[position][2]);

                    holder.linearLayout_1.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            float from = 0;
                            float to = 0;
                            boolean now = false;

                            switch (event.getAction()) {
                                case MotionEvent.ACTION_DOWN:
                                    if (!now) {
                                        now = true;
                                        from = event.getY();
                                        timer = new HoldTimer(1000, 100, holder.textView1Form1, holder.textView2Form1, holder.textView3Form1);
                                        timer.start();

                                        holder.textView1Form1.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                                        holder.textView2Form1.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                                        holder.textView3Form1.setBackgroundColor(mContext.getResources().getColor(R.color.red));

                                        return true;
                                    }
                                    break;

                                case MotionEvent.ACTION_MOVE:
                                    to = event.getY();

                                    if (((from - to) > HEIGHT) | ((from - to) < HEIGHT)) {
                                        timer.cancel();

                                        holder.textView1Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                        holder.textView2Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                        holder.textView3Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));

                                        now = false;
                                        return true;
                                    }
                                    break;
                                case MotionEvent.ACTION_UP:
                                    timer.cancel();

                                    holder.textView1Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                    holder.textView2Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                    holder.textView3Form1.setBackgroundColor(mContext.getResources().getColor(R.color.white));

                                    now = false;
                                    return true;
                            }
                            return false;
                        }
                    });
                    break;

                case SECOND_WORDS:
                    holder.textView1Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][0]);
                    holder.textView2Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][1]);
                    holder.textView3Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][2]);
                    holder.textView4Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][3]);
                    holder.textView5Form2.setText(mWordsForm2[position - FIRST_ARRAY_LENGTH][4]);
                    holder.linearLayout_2.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            float from = 0;
                            float to = 0;
                            boolean now = false;

                            switch (event.getAction()) {
                                case MotionEvent.ACTION_DOWN:
                                    if (!now) {
                                        now = true;
                                        from = event.getY();
                                        timer = new HoldTimer(1000, 100, holder.textView1Form2, holder.textView2Form2, holder.textView3Form2, holder.textView4Form2, holder.textView5Form2);
                                        timer.start();

                                        holder.textView1Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                                        holder.textView2Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                                        holder.textView3Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                                        holder.textView4Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));
                                        holder.textView5Form2.setBackgroundColor(mContext.getResources().getColor(R.color.red));

                                        return true;
                                    }
                                    break;

                                case MotionEvent.ACTION_MOVE:
                                    to = event.getY();

                                    if (((from + HEIGHT) < to) | ((from - HEIGHT) > to)) {
                                        timer.cancel();

                                        holder.textView1Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                        holder.textView2Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                        holder.textView3Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                        holder.textView4Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                        holder.textView5Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));

                                        now = false;
                                        return true;
                                    }
                                    break;
                                case MotionEvent.ACTION_UP:
                                    timer.cancel();

                                    holder.textView1Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                    holder.textView2Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                    holder.textView3Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                    holder.textView4Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));
                                    holder.textView5Form2.setBackgroundColor(mContext.getResources().getColor(R.color.white));

                                    now = false;
                                    return true;
                            }
                            return false;
                        }
                    });
                    break;
            }
            return convertView;
        }

        @Override
        public int getCount() {
            return (mWordsForm1.length + mWordsForm2.length);
        }

        @Override
        public int getItemViewType(int position) {
            return (position < mWordsForm1.length) ? FIRST_WORDS : SECOND_WORDS;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public Object getItem(int position) {
            String[][] item = new String[1][8];

            item[0][0] = mWordsForm1[position][0];
            item[0][1] = mWordsForm1[position][1];
            item[0][2] = mWordsForm1[position][2];

            item[0][3] = mWordsForm2[position][0];
            item[0][4] = mWordsForm2[position][1];
            item[0][5] = mWordsForm2[position][2];
            item[0][6] = mWordsForm2[position][3];
            item[0][7] = mWordsForm2[position][4];
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        static class ViewHolder {
            public TextView textView1Form1;
            public TextView textView2Form1;
            public TextView textView3Form1;
            public TextView textView1Form2;
            public TextView textView2Form2;
            public TextView textView3Form2;
            public TextView textView4Form2;
            public TextView textView5Form2;
            public LinearLayout linearLayout_1;
            public LinearLayout linearLayout_2;
        }

        private class HoldTimer extends CountDownTimer {
            private TextView text1;
            private TextView text2;
            private TextView text3;
            private TextView text4;
            private TextView text5;
            private boolean form;

            public HoldTimer(long millisInFuture, long countDownInterval, TextView text1, TextView text2, TextView text3) {
                super(millisInFuture, countDownInterval);

                this.text1 = text1;
                this.text2 = text2;
                this.text3 = text3;

                form = true;
            }

            public HoldTimer(long millisInFuture, long countDownInterval, TextView text1, TextView text2, TextView text3, TextView text4, TextView text5) {
                super(millisInFuture, countDownInterval);

                this.text1 = text1;
                this.text2 = text2;
                this.text3 = text3;
                this.text4 = text4;
                this.text5 = text5;

                form = false;
            }

            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                ViewHolder holder = new ViewHolder();

                if (form) {
                    text1.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                    text2.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                    text3.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                } else {
                    text1.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                    text2.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                    text3.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                    text4.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                    text5.setBackgroundColor(mContext.getResources().getColor(R.color.gray));
                }
            }
        }
    }
5
  • Это принципы List элементов, Если не брать 3-й пункт, то можно лекго использовать ListView, будет немного кода и работать отлично с Вашим списком (по производительности). А с 3-м пунктом надо пошаманить, но думаю тоже просто. А можно использовать RecyclerView и там это делается всё, с наимацией не будет проблем. ПРосто так как у Вас взаимодействие с БД, кода будет в раза 3 больше. 7 ноя 2015 в 13:01
  • @ShwarzAndrei, вот именно с 3м пунктом у меня ничего не выходит (он совсем не так, как должен работает). А RecyclerView я посмотрю вечером, он вообще быстрый?
    – user189127
    7 ноя 2015 в 13:31
  • Мне очень нравится работать с новым списком Recycler, но скажу сразу, что есть ошибочки которые думаю пофиксят со временем. Но вот в плане анимации, и внешнего вида там всё очень красиво, всё, что фантазии угодно. В плане производительности, здесь отдельный разговор, но сама структура создания RecyclerView делает его быстрей. Кстати по вашему эффекту я видел анимацию на GitHub попробуйте, забить по поиску типо SwapToRemove. Удачи. 7 ноя 2015 в 14:23
  • @ShwarzAndrei, я нашел только это — github.com/FavishInc/swipe-to-remove
    – user189127
    7 ноя 2015 в 14:43
  • @ShwarzAndrei, до меня дошло. Пока читал про RecycleView узнал, что есть слушатель (у ListView), который перехватывает выделение элемента, поэтому background нужно менять в нем! Если не разберусь с RecycleView — буду дальше делать все через ListView.
    – user189127
    7 ноя 2015 в 23:34

1 ответ 1

1
  1. Нужен selector: http://www.compiletimeerror.com/2014/03/android-button-selector-tutorial-with.html
  2. Простой setOnItemLongClickListener()
  3. Третий пункт не совсем понятен и тем более не ясно для чего нужен такой функционал...
3
  • Третий пункт: когда пользователь хочет просто пролистнуть список, у меня выходит, что он его удерживает и вызывается контекстное меню, а так нельзя :).
    – user189127
    9 ноя 2015 в 7:57
  • Странно, потому что у меня в моём ListView если при удержании перелистнуть список, то нажатие автоматически спадает 9 ноя 2015 в 8:19
  • Проблема в том, что у меня свой background и выделение, при нажатии, не работает. Поэтому мне нужно и изменить цвет и обработать нажатие. Только сейчас до меня дошло, что нужно выделение обрабатывать через onTouch'ем, а нажатие onItem'ом! Я все это пытался проделать через адаптер для каждого View в onTouch. Сейчас попробую разделить, но изменение цвета ведет себя немного не адекватно из-за ViewHolder...
    – user189127
    9 ноя 2015 в 8:23

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.