Chuyển đến nội dung chính

Tạo Spinner lọc theo từ khoá nhập vào

https://www.androidtutorialpoint.com/material-design/android-spinner-search-implementation/

The UI Will appear like this:
 

Creating Project – SearchableSpinner

  1. Open your Android Studio & create a new Project CustomSearch, we are using androidtutorial.com as our domain name but you may leave it as default and also we have taken Blank Activity for this project, you may go according to your requirements.
  2. The name for activity is by default MainActivity, and we have kept all the things by default and then clicked finish.
After the project is created and Gradle dependencies are resolved, you may start.

Add Gradle Dependencies

Build.gradle(Module: app )

1
2
3
4
5
6
dependencies {    
compile fileTree(dir: 'libs', include: ['*.jar'])  
testCompile 'junit:junit:4.12'    
compile 'com.android.support:appcompat-v7:25.1.1'    
compile 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1'
}

Creating Layout

activity_main.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#E81D62">
 
    <com.toptoche.searchablespinnerlibrary.SearchableSpinner android:id="@+id/spinner_search" android:layout_width="wrap_content" android:layout_height="50dp" />
 
    <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/spinner_search" android:background="#212121">
    </LinearLayout>
 
</RelativeLayout>
We have assigned spinner id as spinner_search, all of the attributes are self-explanatory but still, you can feel free to ask anything in the comment section below.

strings.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<resources>
    <string name="app_name">SpinnerSearch</string>
    <string-array name="mobile_manufacturers">
        <item>Select one Item</item>
        <item>Samsung</item>
        <item>Foxconn</item>
        <item>Apple</item>
        <item>Oppo</item>
        <item>Nokia</item>
        <item>LYF</item>
        <item>Xiaomi</item>
        <item>Huawei</item>
        <item>Asus</item>
        <item>Lenovo</item>
    </string-array>
</resources>
We need a list of String items for this.So we have made a string-array in strings.xml and we will assign this data later on to our Spinner in MainActivity.java

Creating Logic

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
<pre>package com.androidtutorialpoint.spinnersearch;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Spinner spinner = (Spinner) findViewById(R.id.spinner_search);
        // Creating ArrayAdapter using the string array and default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.mobile_manufacturers, android.R.layout.simple_spinner_item);
        // Specify layout to be used when list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Applying the adapter to our spinner
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
    }
 
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String selectedItem = parent.getItemAtPosition(position).toString();
        switch (selectedItem) {
            case "Select one Item":
                break;
            case "Samsung":
                Toast.makeText(getApplicationContext(), selectedItem + " in Korean means 3 Stars!", Toast.LENGTH_SHORT).show();
                break;
            case "Foxconn":
                Toast.makeText(getApplicationContext(), selectedItem + " is world's largest contract electronics manufacturer", Toast.LENGTH_SHORT).show();
                break;
            case "Apple":
                Toast.makeText(getApplicationContext(), selectedItem + " was founded in 1976!", Toast.LENGTH_SHORT).show();
                break;
            case "Oppo":
                Toast.makeText(getApplicationContext(), selectedItem + " made first phone that can make 50MP photos", Toast.LENGTH_SHORT).show();
                break;
            case "Nokia":
                Toast.makeText(getApplicationContext(), selectedItem + " was founded 151 years ago!", Toast.LENGTH_SHORT).show();
                break;
            case "LYF":
                Toast.makeText(getApplicationContext(), selectedItem + " is an Indian Mobile Handset company", Toast.LENGTH_SHORT).show();
                break;
            case "Xiaomi":
                Toast.makeText(getApplicationContext(), selectedItem + " is world's 4th largest smartphone maker!", Toast.LENGTH_SHORT).show();
                break;
            case "Huawei":
                Toast.makeText(getApplicationContext(), selectedItem + " is largest telecommunications equipment manufacturer in the World! ", Toast.LENGTH_SHORT).show();
                break;
            case "Asus":
                Toast.makeText(getApplicationContext(), selectedItem + " name came from word PEGASUS", Toast.LENGTH_SHORT).show();
                break;
            case "Lenovo":
                Toast.makeText(getApplicationContext(), selectedItem + " is largest PC vendor by unit sales", Toast.LENGTH_SHORT).show();
                break;
        }
    }
 
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
 
    }
}</pre>
We are using ArrayAdapter object using string array and a default spinner layout. by using spinner.setAdapter(adapter) we will now apply the adapter to the spinner.
By using onItemSelectedListener we will apply a small logic by fetching Item name at a certain position (i.e position of the item which was clicked). We can’t use position, instead, we use item name in our switch case. After searching, the list will be filtered and hence the item’s position is now changed, so wrong output will be there, if we use position to raise Toast or do anything. Hence, we will use Item name which will be a string value to show appropriate Toasts. This approach is more appropriate for this implementation.
That’s it! Now you can run the app and see the changes yourself. In case of any queries you can comment your doubts below!

Nhận xét

Bài đăng phổ biến từ blog này

Camera2 - Android

Ở bài viết này mình xin giới thiệu về cách sử dụng Camera2 trong android SDK 21. Với các lập trình viên android việc sử dụng Camera có rất nhiều trong ứng dụng: Camera Capture Images, Barcode - QR Code Reader, AR, Video Record,.... Nhiều ứng dụng chỉ ở tầng ứng dụng sử dụng thông qua  Intent  như vậy hệ thống tự động được gọi ở mức tối ưu nhất, nhưng cũng không ít ứng dụng cần can thiệp vào tầng  native  để xử lý Với  Camera   developer.android.com  đã  deprecate  nó đã không còn được sử dụng cơ bản trong các ứng dụng nữa vì rất nhiều nguyên nhân trong đó phải kể tới: tốn tài nguyên, thời gian capture khá chậm và đặc biệt phục vụ nhu cầu ngày càng cao của người dùng như 'Chụp ảnh liên tục, chụp nhiều ảnh và tự động lấy nét' thì  Camera không đáp ứng được Với  Camera2  đã đáp ứng được những thiếu xót trên ngoài ra việc customize cho ảnh là rất dễ dàng mang lại chất lượng cao ngoài ra việc sử dụng cũng không có nhiều thay ...

Sự khác nhau giữa let, apply, with, run và also trong Kotlin

Với những ai đã sử dụng Kotlin để phát triển ứng dụng, chắc hẳn đã không ít lần sử dụng các standard functions run, with, let, also và apply. Để hiểu và sử dụng thành thục chúng không phải là dễ. Và dưới đây là những điều đúc kết lại được. https://viblo.asia/p/su-khac-nhau-giua-let-apply-with-run-va-also-trong-kotlin-RQqKLNdml7z Scoping functions Có thể hiểu đơn giản, scoping function là phạm vi ảnh hưởng nhất định của một hàm. Nó là điều cốt lõi để phân biệt giữa các scoping functions: run, with, T.run, T.let, T.also và T.apply. Dưới đây là minh hoạ phạm vi của hàm run: fun test ( ) { var mood = "I am sad" run { val mood = "I am happy" println ( mood ) // I am happy } println ( mood ) // I am sad } Ở trên, ta có thể thấy rõ ràng trong phạm vi của hàm run, biến mood đã được định nghĩa lại trước khi in ra mà không làm ảnh hưởng tới phần khác của chương trình 3 attributes of scoping functions 1.Normal vs. extension fun...

TỰ ĐỘNG HUỶ ACTIVITY SAU KHI STARTACTIVITY

Trước giờ để huỷ một Activity khi bạn thường dùng hàm  finish()  đúng không nào? Không đi đâu xa là khi bạn Intent từ một Activity này sang Activity khác mà muốn huỷ luôn Activity đầu tiên luôn thì bạn sẽ dùng đoạn code y chang bên dưới chứ? Cơ chế của Activity là khi bạn chuyển từ một Activity này sáng Activity khác thì nó sẽ Activity đó vào stack, và khi back về thì Activity sẽ được hiện lên lại và chạy vào onResume(), nếu bạn chưa hiểu về  vòng đời của Activity  thì xem lại bài viết kèm video tại blog mình nhé, mình ví dụ khá chi tiết. Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); finish(); Đoạn code trên nghĩa là chuyển từ MainActivity sang LoginActivity và sau đó huỷ luôn MainActivity đúng không nào? Tuy nhiên đó không phải là cách duy nhất mà chúng ta làm đâu bởi Android hỗ trợ chúng ta một số thuộc tính mà bạn không phải dùng code Java để làm. Không lưu Activity vào stack Cũng logic như bài toán phí...