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

NHỮNG WIDGET THƯỜNG DÙNG TRONG FLUTTER

 https://baoflutter.com/nhung-widget-thuong-dung-trong-flutter/ Trong bài viết trước về  cách xây dựng màn hình ứng dụng Flutter , các bạn biết rằng các màn hình ứng dụng được tạo ra bởi các widget ghép lại với nhau. Vì vậy việc hiểu và sử dụng các Widget là rất quan trọng. Vì vậy trong bài viết này, tôi sẽ giới thiệu cho các bạn về những widget quan trọng trong Flutter. Hầu hết các Widget đều có các phần sau đây: + Đặc tính của Widget như : color, theme, height, weight, decoration, onTap, onPressed + Liên kết với các Widget khác với từ khoá: child, children, home hoặc body Ví dụ : 1 2 3 4 5 6 Container ( color : Colors . blue , height : 300 , weight : 300 , child : Text ( "Widget con" ) , ) Khi làm một số App cơ bản, bạn sẽ nắm chắc được cách sử dụng các Widget hay dùng. MaterialApp – Là widget rất liện lợi, cung cấp các widget cho việc xây dựng ứng dụng sử dụng thư viện Material Design UI của google. – Widget này được sử dụng trong hàm build đầu tiên của hầu hết các ứn...

Get Current location using FusedLocationProviderClient in Android

Hello to coders, Previously we have taught you  how you get current location using GPS/Network Provider . Then android has revealed  FusedLocationProviderClient  under  GoogleApi . FusedLocationProviderClient is for interacting with the location using fused location provider. ( NOTE :   To use this feature, GPS must be turned on your device. For manually ask the user to turn on GPS, please check  next article ) So let’s get started for the tutorial for getting the current location. First, add a dependency for location by play services: implementation 'com.google.android.gms:play-services-location:15.0.1' Then define FusedLocationProviderClient: private FusedLocationProviderClient mFusedLocationClient; private TextView txtLocation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout. activity_main ); this.txtLocation = (TextView) findViewById(R.id. txtLocat...

Get You Last known Location & Current Location using FusedLocationProviderClient

NOVEMBER 30, 2017 Get You Last known Location & Current Location using FusedLocationProviderClient        I would like to cover very basic and simple example of retreiving last known location & Current Location  using Fused location API.  I have written many example for fused location API in my previous posts but in this post i will show how to get retrieve the location  without implementing Google Api Client . All these magics happen after the release of version  11.0.0 of Google Play services SDK. FusedLocationProviderApi is Deprecated We have previously used following way to retrieve the last known location. mLastLocation  =  LocationServices. FusedLocationApi . getLastLocation ( mGoogleApiClient ) ; We no need to define LocationServices. FusedLocationApi  anymore. it is deprecated. It will be removed in the future release. Instead You can use LocationServi...