Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.77/13: Рейтинг темы: голосов - 13, средняя оценка - 4.77
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
1

Поиск как в браузере

02.05.2016, 17:23. Показов 2521. Ответов 21
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Доброго времени суток!
Столкнулся с проблемой, что не могу найти примеров реализации поиска. Второй день уже ищу и безрезультатно. Смысл поиска: Поиск как в браузере, когда тебя переносит по найденным совпадениям в тексте и подсвечивает их. Нашел кучу реализаций поиска для ListView и прочее. Но мне нужен именно вот такой "браузерный" поиск.
У меня на activity расположено несколько TextView, который все вместе с RelativeLayout, в котором они находятся, запихнуты в ScrollView. Один из этих TextView них содержит очень много текста. И, чтобы по нему легче было ориентироваться, я хотел бы прикрутить поиск, который бы просто переносил пользователя к той части этого TextView, в котором есть то, что он запросил. В общем обычный Ctrl+F.
Можно ли это как-то реализовать?
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
02.05.2016, 17:23
Ответы с готовыми решениями:

Перенаправляется поиск в браузере, много рекламы в браузере
Здравствуйте! Все как и во многих сообщениях ниже. Скачала какую-то байду, установился Амиго с...

Как реализовать поиск в браузере ?
Имеем код который через monkeyrunner открывает нужную ссылку в браузере телефона на базе Android :...

Как в браузере Тор включить автозаполнение форм и автосохранение паролей, как добавить поиск от яндекс?
Собственно, всё в вопросе!

Как удалить поиск getsearch в браузере GoogleChrome?
Здравствуйте. В настройках браузера появился некий поиск "GetSearch", я не могу его ни удалить, ни...

21
2883 / 2295 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
02.05.2016, 19:47 2
мне стало интересно и я накидал простой примерчик
работает поиск и кнопки - next/prev
пока что не знаю как сделать по-человечески автоматическую прокрутку текста если его много, но думаю что для начала и так сойдет

минимально необходимый код в активити
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.example.mytestapplication;
 
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class MainActivity extends AppCompatActivity {
 
    private final ArrayList<Integer> posList = new ArrayList<>();
    private int current;
    private TextView tv;
    private BackgroundColorSpan colorSpan;
    private EditText et;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        colorSpan = new BackgroundColorSpan(ContextCompat.getColor(this, R.color.colorAccent));
        tv = (TextView) findViewById(R.id.textView);
        findViewById(R.id.nextButton).setOnClickListener(btnClickListener);
        findViewById(R.id.prevButton).setOnClickListener(btnClickListener);
        et = (EditText) findViewById(R.id.editText);
        et.addTextChangedListener(textWatcher);
    }
 
    private final View.OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.nextButton) current++;
            else current--;
            if (current < 0) current = posList.size() - 1;
            else if (current >= posList.size()) current = 0;
            findOccurrence();
        }
    };
 
    private final TextWatcher textWatcher = new TextWatcher() {
 
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
 
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
 
        @Override
        public void afterTextChanged(Editable s) {
            posList.clear();
            Pattern p = Pattern.compile(s.toString());
            Matcher m = p.matcher(tv.getText().toString());
            while (m.find()) posList.add(m.start());
            current = 0;
            findOccurrence();
        }
    };
 
    private void findOccurrence() {
        String where = tv.getText().toString();
        if (posList.isEmpty()) {
            tv.setText(where);
        } else {
            Spannable selectSpan = new SpannableString(where);
            int spanStart = posList.get(current);
            int spanEnd = spanStart + et.getText().toString().length();
            selectSpan.setSpan(colorSpan, spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(selectSpan);
        }
    }
}

разметка на которой тренировался
Кликните здесь для просмотра всего текста
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
 
        <Button
            android:id="@+id/prevButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Prev" />
 
        <Button
            android:id="@+id/nextButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Next" />
 
    </LinearLayout>
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/dummy_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />
 
</LinearLayout>

"@string/dummy_text" - любой длинный текст
Поиск как в браузере

если клацать кнопки next/prev то будет искать вхождения "по кругу"
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
02.05.2016, 20:16  [ТС] 3
Паблито, Да, я находил пример с подсветкой простенький. Ваш намного, конечно лучше. Но вся загвоздка именно в прыжке к тому месту в тексте, которое является "искаемым" куском.
0
2883 / 2295 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
03.05.2016, 11:21 4
теперь прыгает, надо поменять метод
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    private void findOccurrence() {
        String where = tv.getText().toString();
        if (posList.isEmpty()) {
            tv.setText(where);
        } else {
            Spannable selectSpan = new SpannableString(where);
            int spanStart = posList.get(current);
            int spanEnd = spanStart + et.getText().toString().length();
            selectSpan.setSpan(colorSpan, spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(selectSpan);
            tv.getDrawingRect(r);
            int bottom = tv.getLayout().getLineBottom(tv.getLayout().getLineForOffset(spanEnd));
            if (bottom > r.height()) tv.scrollTo(0, bottom - r.height());
            if (bottom < r.height()) tv.scrollTo(0, 0);
        }
    }
и добавить поле в активити
Java
1
    private final Rect r = new Rect();
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 12:26  [ТС] 5
Паблито, странно, у меня ругается вот так, как только я начинаю набирать текст в поле поиска:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.text.Layout.getLineForOffset(int)' on a null object reference
на строчку
Java
1
int bottom = tv.getLayout().getLineBottom(tv.getLayout().getLineForOffset(spanEnd));
Возможно, я не правильно понял и вставил вот эту часть:
и добавить поле в активити
Java
1
private final Rect r = new Rect();
0
2883 / 2295 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
03.05.2016, 12:29 6
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.example.mytestapplication;
 
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class MainActivity extends AppCompatActivity {
 
    private final ArrayList<Integer> posList = new ArrayList<>();
    private int current;
    private TextView tv;
    private BackgroundColorSpan colorSpan;
    private EditText et;
    private final Rect r = new Rect();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        colorSpan = new BackgroundColorSpan(ContextCompat.getColor(this, R.color.colorAccent));
        tv = (TextView) findViewById(R.id.textView);
        tv.setMovementMethod(new ScrollingMovementMethod());
 
        findViewById(R.id.nextButton).setOnClickListener(btnClickListener);
        findViewById(R.id.prevButton).setOnClickListener(btnClickListener);
        et = (EditText) findViewById(R.id.editText);
        et.addTextChangedListener(textWatcher);
    }
 
    private final View.OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.nextButton) current++;
            else current--;
            if (current < 0) current = posList.size() - 1;
            else if (current >= posList.size()) current = 0;
            findOccurrence();
        }
    };
 
    private final TextWatcher textWatcher = new TextWatcher() {
 
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
 
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
 
        @Override
        public void afterTextChanged(Editable s) {
            posList.clear();
            Pattern p = Pattern.compile(s.toString());
            Matcher m = p.matcher(tv.getText().toString());
            while (m.find()) posList.add(m.start());
            current = 0;
            findOccurrence();
        }
    };
 
    private void findOccurrence() {
        String where = tv.getText().toString();
        if (posList.isEmpty()) {
            tv.setText(where);
        } else {
            Spannable selectSpan = new SpannableString(where);
            int spanStart = posList.get(current);
            int spanEnd = spanStart + et.getText().toString().length();
            selectSpan.setSpan(colorSpan, spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(selectSpan);
            tv.getDrawingRect(r);
            int bottom = tv.getLayout().getLineBottom(tv.getLayout().getLineForOffset(spanEnd));
            if (bottom > r.height()) tv.scrollTo(0, bottom - r.height());
            if (bottom < r.height()) tv.scrollTo(0, 0);
        }
    }
}
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 12:39  [ТС] 7
Странно, собрал пустой проект с этим кодом - оно хотя бы не вырубается. Но прыжок все равно не работает. Эхх, странно. Ладно, буду пытаться разобраться
0
2883 / 2295 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
03.05.2016, 12:53 8
http://screencast.com/t/pSRqn2FCnL
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 12:56  [ТС] 9
Бррр, совсем не понимаю. Я просто взял код и полностью вставил в пустой проект, накидав layout как надо и вставив строку. Ну и результат вы видели на гифке, что я скинул ранее. А вы никаких манипуляций с layout или еще чем-нибудь не делали?
Плюс, я просмотрел как меняется spanEnd в моем проекте, и он точно не имеет нулевое значение, не понимаю, почему эта ошибка появляется.
0
2883 / 2295 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
03.05.2016, 12:57 10
увидеть бы код активити и разметки, актуальный
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 12:59  [ТС] 11
Кликните здесь для просмотра всего текста
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="7dp"
    android:scrollbars="none" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
 
        <Button
            android:id="@+id/prevButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Prev" />
 
        <Button
            android:id="@+id/nextButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Next" />
 
    </LinearLayout>
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/dummy_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />
 
</LinearLayout>
</ScrollView>
0
Pablito
03.05.2016, 13:06
  #12

Не по теме:

я моем примере нет скроллвью, без него работает
чуток позже попробую переделать как надо

0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 13:09  [ТС] 13
Пабилто,
Да почему, совсем по делу. Ибо в данном случае ScrollView очень важен. То есть я должен быть способен читать спокойно весь текст. Или же попробовать найти, если не хочу перековыривать весь текст. А поскольку TextView у меня несколько, а большое количество текста только в одном, то я их всех вместе впихнул в ScrollView.
Буду очень благодарен, если вы попробуете
Я пока попробую понять, почему в моем проекте выдается эта ошибка.
0
2883 / 2295 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
03.05.2016, 14:59 14
Лучший ответ Сообщение было отмечено Retper как решение

Решение

так работает
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
 
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class MainActivity extends AppCompatActivity {
 
    private final ArrayList<Integer> posList = new ArrayList<>();
    private int current;
    private TextView tv;
    private BackgroundColorSpan colorSpan;
    private EditText et;
    private final Rect r = new Rect();
    private ScrollView scrollView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        colorSpan = new BackgroundColorSpan(ContextCompat.getColor(this, R.color.colorAccent));
        tv = (TextView) findViewById(R.id.textView);
//        tv.setMovementMethod(new ScrollingMovementMethod());
 
        findViewById(R.id.nextButton).setOnClickListener(btnClickListener);
        findViewById(R.id.prevButton).setOnClickListener(btnClickListener);
        et = (EditText) findViewById(R.id.editText);
        et.addTextChangedListener(textWatcher);
        scrollView = (ScrollView) findViewById(R.id.scrollView1);
    }
 
    private final View.OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.nextButton) current++;
            else current--;
            if (current < 0) current = posList.size() - 1;
            else if (current >= posList.size()) current = 0;
            findOccurrence();
        }
    };
 
    private final TextWatcher textWatcher = new TextWatcher() {
 
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
 
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
 
        @Override
        public void afterTextChanged(Editable s) {
            posList.clear();
            Pattern p = Pattern.compile(s.toString());
            Matcher m = p.matcher(tv.getText().toString());
            while (m.find()) posList.add(m.start());
            current = 0;
            findOccurrence();
        }
    };
 
    private void findOccurrence() {
        String where = tv.getText().toString();
        if (posList.isEmpty()) {
            tv.setText(where);
        } else {
            Spannable selectSpan = new SpannableString(where);
            int spanStart = posList.get(current);
            int spanEnd = spanStart + et.getText().toString().length();
            selectSpan.setSpan(colorSpan, spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(selectSpan);
            scrollView.getDrawingRect(r);
            int bottom = tv.getLayout().getLineBottom(tv.getLayout().getLineForOffset(spanEnd));
            if (bottom > r.height()) scrollView.scrollTo(0, bottom - r.height() + scrollView.getPaddingBottom() + scrollView.getPaddingTop());
            if (bottom < r.height()) scrollView.scrollTo(0, 0);
        }
    }
}

Кликните здесь для просмотра всего текста
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
 
        <Button
            android:id="@+id/prevButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Prev" />
 
        <Button
            android:id="@+id/nextButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Next" />
 
    </LinearLayout>
 
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="7dp"
        android:scrollbars="none">
 
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/dummy_text"
            android:textAppearance="@style/TextAppearance.AppCompat.Large" />
    </ScrollView>
    
</LinearLayout>


Цитата Сообщение от Retper Посмотреть сообщение
почему в моем проекте выдается эта ошибка
надо видеть код
1
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 15:49  [ТС] 15
Паблито

Не по теме:

Чтобы просто по каждой мелочи не спрашивать вас, а попытаться самому исправить, пытаюсь понять, как работает то, что вы сделали. Но моих познаний никак не хватает :( Поэтому пишу:


Странно, что если сделать так, что весь Layout находится внутри ScrollView, то перескок ошибается на пару строк и не достает. Не получилось самому устранить. А так да, ваш код шикарно работает, когда TextView находится внутри ScrollView.
Исправить ошибку с вставкой вашего поиска в свой проект так и не получилось. Такое ощущение, что ошибка какая-то простая и я просто что-то недоглядел. Но не знаю. Вот код моего проекта (не знаю, может по какой-то причине понадобятся все классы):
3 класса:
1) DatabaseHelper:
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.example.admin.vkr;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
 
public class DatabaseHelper extends SQLiteOpenHelper implements BaseColumns {
    private static String DB_PATH = "/data/data/com.example.admin.vkr/databases/";
    private static String DB_NAME = "games.db";
    private static final int SCHEMA = 1; // версия базы данных
    static final String TABLE1 = "names";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "game_name";
    static final String TABLE2 = "games";
    public static final String COLUMN_GAME_NAME = "name";
    public static final String COLUMN_RELEASE_DATE = "release_date";
    public static final String COLUMN_GENRE = "genre";
    public static final String COLUMN_WALKTHROUGH = "walkthrough";
    public SQLiteDatabase database;
    private Context myContext;
 
    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, SCHEMA);
        this.myContext=context;
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion,  int newVersion) {
 
    }
 
    public void create_db(){
        InputStream myInput = null;
        OutputStream myOutput = null;
        try {
            File file = new File(DB_PATH + DB_NAME);
            if (!file.exists()) {
                this.getReadableDatabase();
                myInput = myContext.getAssets().open(DB_NAME);
                String outFileName = DB_PATH + DB_NAME;
                myOutput = new FileOutputStream(outFileName);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = myInput.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
 
                myOutput.flush();
                myOutput.close();
                myInput.close();
            }
        }
        catch(IOException ex){
 
        }
    }
    public void open() throws SQLException {
        String path = DB_PATH + DB_NAME;
        database = SQLiteDatabase.openDatabase(path, null,
                SQLiteDatabase.OPEN_READWRITE);
 
    }
 
    @Override
    public synchronized void close() {
        if (database != null) {
            database.close();
        }
        super.close();
    }
}

2) game (здесь как раз и реализуется поиск)
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package com.example.admin.vkr;
 
import android.database.Cursor;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class game extends AppCompatActivity {
    DatabaseHelper sqlHelper;
    String name;
    private final ArrayList<Integer> posList = new ArrayList<>();
    private int current;
    private TextView tv;
    private BackgroundColorSpan colorSpan;
    private EditText et;
    private final Rect r = new Rect();
    private ScrollView scrollView;
 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);
        name = getIntent().getExtras().getString("name");
        sqlHelper = new DatabaseHelper(getApplicationContext());
        sqlHelper.create_db();
        colorSpan = new BackgroundColorSpan(ContextCompat.getColor(this, R.color.colorAccent));
        tv = (TextView) findViewById(R.id.walkthrough);
        //tv.setMovementMethod(new ScrollingMovementMethod());
        findViewById(R.id.nextButton).setOnClickListener(btnClickListener);
        findViewById(R.id.prevButton).setOnClickListener(btnClickListener);
        et = (EditText) findViewById(R.id.editText);
        et.addTextChangedListener(textWatcher);
        scrollView = (ScrollView) findViewById(R.id.scrollView1);
    }
 
    private final View.OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.nextButton) current++;
            else current--;
            if (current < 0) current = posList.size() - 1;
            else if (current >= posList.size()) current = 0;
            findOccurrence();
        }
    };
 
    private final TextWatcher textWatcher = new TextWatcher() {
 
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
 
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
 
        @Override
        public void afterTextChanged(Editable s) {
            posList.clear();
            Pattern p = Pattern.compile(s.toString());
            Matcher m = p.matcher(tv.getText().toString());
            while (m.find()) posList.add(m.start());
            current = 0;
            findOccurrence();
        }
    };
 
    private void findOccurrence() {
        String where = tv.getText().toString();
        if (posList.isEmpty()) {
            tv.setText(where);
        } else {
            Spannable selectSpan = new SpannableString(where);
            int spanStart = posList.get(current);
            int spanEnd = spanStart + et.getText().toString().length();
            selectSpan.setSpan(colorSpan, spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv.setText(selectSpan);
            scrollView.getDrawingRect(r);
            int bottom = tv.getLayout().getLineBottom(tv.getLayout().getLineForOffset(spanEnd));
            if (bottom > r.height()) scrollView.scrollTo(0, bottom - r.height() + scrollView.getPaddingBottom() + scrollView.getPaddingTop());
            if (bottom < r.height()) scrollView.scrollTo(0, 0);
        }
    }
 
    public void onResume() {
        super.onResume();
        try {
            sqlHelper.open();
            String query = "select * from " + DatabaseHelper.TABLE2 + " where " +
                    DatabaseHelper.COLUMN_GAME_NAME + " like '" + name + "'";
            Cursor cursor2 = sqlHelper.database.rawQuery(query, null);
            cursor2.moveToFirst();
            String gameName = cursor2.getString(cursor2.getColumnIndex(DatabaseHelper.COLUMN_GAME_NAME));
            String releaseDate = cursor2.getString(cursor2.getColumnIndex(DatabaseHelper.COLUMN_RELEASE_DATE));
            String genre = cursor2.getString(cursor2.getColumnIndex(DatabaseHelper.COLUMN_GENRE));
            String walkthrough = cursor2.getString(cursor2.getColumnIndex(DatabaseHelper.COLUMN_WALKTHROUGH));
            TextView nameTextView = (TextView) findViewById(R.id.name);
            nameTextView.setText(gameName);
            TextView releaseTextView = (TextView) findViewById(R.id.release_date);
            releaseTextView.setText(releaseDate);
            TextView genreTextView = (TextView) findViewById(R.id.genre);
            genreTextView.setText(genre);
            tv.setText(Html.fromHtml(walkthrough), TextView.BufferType.SPANNABLE);
            cursor2.close();
        }
        catch (SQLException ex) {}
    }
}

3) MainActivity
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.example.admin.vkr;
 
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
 
import java.sql.SQLException;
 
public class MainActivity extends AppCompatActivity{
    ListView lv;
    EditText userFilter;
    DatabaseHelper sqlHelper;
    Cursor userCursor;
    SimpleCursorAdapter userAdapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        lv = (ListView)findViewById(R.id.userList);
        userFilter = (EditText)findViewById(R.id.userFilter);
        sqlHelper = new DatabaseHelper(getApplicationContext());
        sqlHelper.create_db();
    }
    @Override
    public void onResume(){
        super.onResume();
        try {
            sqlHelper.open();
            userCursor = sqlHelper.database.rawQuery("select * from " + DatabaseHelper.TABLE1, null);
            String[] headers = new String[]{DatabaseHelper.COLUMN_NAME};
            userAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item,
                    userCursor, headers, new int[]{android.R.id.text1}, 0);
            if(!userFilter.getText().toString().isEmpty())
                userAdapter.getFilter().filter(userFilter.getText().toString());
 
            userFilter.addTextChangedListener(new TextWatcher() {
 
                public void afterTextChanged(Editable s) {
                }
 
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }
                // при изменении текста выполняем фильтрацию
                public void onTextChanged(CharSequence s, int start, int before, int count) {
 
                    userAdapter.getFilter().filter(s.toString());
                }
            });
 
            userAdapter.setFilterQueryProvider(new FilterQueryProvider() {
                @Override
                public Cursor runQuery(CharSequence constraint) {
 
                    if (constraint == null || constraint.length() == 0) {
 
                        return sqlHelper.database.rawQuery("select * from " + DatabaseHelper.TABLE1, null);
                    }
                    else {
                        return sqlHelper.database.rawQuery("select * from " + DatabaseHelper.TABLE1 + " where " +
                                DatabaseHelper.COLUMN_NAME + " like ?", new String[]{"%" + constraint.toString() + "%"});
                    }
                }
            });
 
            lv.setAdapter(userAdapter);
        }
        catch (SQLException ex){}
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View itemClicked, int position,
                                    long my_id) {
                Intent intent = new Intent(MainActivity.this, game.class);
                Cursor mycursor = (Cursor) getListView().getItemAtPosition(position);
                intent.putExtra("name", mycursor.getString(1));
                startActivity(intent);
            }
        });
    }
 
    @Override
    public void onDestroy(){
        super.onDestroy();
        sqlHelper.database.close();
        userCursor.close();
    }
 
    public AdapterView getListView() {
        return lv;
    }
}
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 15:49  [ТС] 16
в 1 сообщение не уместилось.
2 activity:
1) mainactivity:
Кликните здесь для просмотра всего текста
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"
    >
    <EditText android:id="@+id/userFilter" android:layout_width="match_parent"
        android:layout_height="wrap_content" android:ems="10"
        android:hint="Поиск"
        />
 
    <ListView
        android:id="@+id/userList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:focusableInTouchMode="true">
    </ListView>
 
</LinearLayout>

2) game (тот, в котором поиск)
Кликните здесь для просмотра всего текста
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="7dp"
    android:scrollbars="none">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"
    >
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Name"
        android:id="@+id/name"
        android:layout_gravity="center_horizontal" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Date"
        android:id="@+id/release_date"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/name" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Genre"
        android:id="@+id/genre"
        android:layout_below="@+id/release_date"/>
 
    <TextView
        android:id="@+id/walkthrough"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Content"
        android:layout_below="@+id/editText"
        android:scrollbars = "vertical"/>
 
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_below="@+id/genre"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/prevButton" />
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="prev"
        android:id="@+id/prevButton"
        android:layout_below="@+id/genre"
        android:layout_toLeftOf="@+id/nextButton" />
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="next"
        android:id="@+id/nextButton"
        android:layout_alignTop="@+id/editText"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>
</ScrollView>


И БД, если вдруг нужна.
0
2883 / 2295 / 769
Регистрация: 12.05.2014
Сообщений: 7,978
03.05.2016, 16:28 17
я в принципе понял из-за чего ошибка, но сейчас вопрос - в приведенной выше разметке получается если нажимать Next то наступает момент когда текст прокручивается вместе с кнопками и уже никак не нажать next

это ведь неудобно
не логичнее было бы сделать так что edit text и кнопки никуда не скролятся?
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
03.05.2016, 17:00  [ТС] 18
Паблито, да, по сути, можно сделать так
Кликните здесь для просмотра всего текста
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
 
        <Button
            android:id="@+id/prevButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Prev" />
 
        <Button
            android:id="@+id/nextButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Next" />
 
    </LinearLayout>
 
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="7dp"
        android:scrollbars="none">
 
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" android:orientation="vertical"
            android:focusable="true"
            android:focusableInTouchMode="true"
            >
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Name"
                android:id="@+id/name"
                android:layout_gravity="center_horizontal" />
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Date"
                android:id="@+id/release_date"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_below="@+id/name" />
 
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="Genre"
                android:id="@+id/genre"
                android:layout_below="@+id/release_date"/>
 
            <TextView
                android:id="@+id/walkthrough"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Content"
                android:layout_below="@+id/genre"
                android:scrollbars = "vertical"/>
        </RelativeLayout>
    </ScrollView>
</LinearLayout>

Я пытался еще запихать поиск вообще в тулбар, но я слишком криворук, там везде в тутроиалах открытие нового активити. А не использование данного.
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
09.05.2016, 10:37  [ТС] 19
С Праздником!
я в принципе понял из-за чего ошибка
Может подтолкнете в нужном направлении?
0
0 / 0 / 0
Регистрация: 28.10.2013
Сообщений: 43
16.05.2016, 15:33  [ТС] 20
Все, изменил приложение так, чтобы все работало. Просто прохождение вытащил в отдельное активити. Спасибо вам, Паблито, за помощь!
0
16.05.2016, 15:33
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
16.05.2016, 15:33
Помогаю со студенческими работами здесь

Ubuntu 16.04 нет звука (как в системе, так и в браузере), видео в браузере проигрывается в ускоренном виде
Добрый день. Проблема на ноуте Asus R209HA при установленной ubuntu (14,16,18): нет звука. На...

Поиск в браузере
Привет,ребят не поможете сделать такую штуку,вообщем у нас есть страничка в браузере и в ней есть...

Delphi поиск в браузере
Друзья, помогите с проблемкой. Мне тут в браузер свой нужно добавить поиск в различных системах как...

Перенаправляется поиск в браузере на go mail
Здравствуйте. В браузере перенаправляется любой поисковый запрос на search engine, затем на...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru