All posts by Sushil

Working with Spinner in Android (Single Selector)

Spinner

Spinners provide a quick way to select one value from a set then we called it a single selector. A spinner shows its currently selected value from set. In the default state, it shows 0 index value from a set. Touching the spinner displays a dropdown menu or dialog with all other available values in the set, So we can be called it a dropdown.

Dropdown

 

 

 

 

 

 

Let’s check, how we can use it in an application.

Spinner integration has 3 key classes:-

1.  Spinner

2. Spinner Adapter

3. Spinner OnItemSelectedListener

So we will discuss above these classes also, with integration. You can add a spinner to your layout XML file. You can use the below sample code –

<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

Spinner Adapter uses for bind between data set and spinner widget and it manages view for the spinner row item. We can use data as an array of string. See sample code –

String[] items = { "Home", "Work", "Other" "Custom"};

Above string array, we will use for the display. So now we need to get reference Spinner which we defined in the XML file. We can use the below sample code –

// reading spinner reference
Spinner spinner = (Spinner) findViewById(R.id.spinner);

So now we need to set values in ArrayAdapter. and We set this ArrayAdapter in Spinner. Use below code –

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
// set Adapter
spinner.setAdapter(adapter);

When the user selects an item from the drop-down, the Spinner object receives an on-item-selected event. for manage event, we can use OnItemSelectedListener in the Spinner. Sample code –

//Register a callback to be invoked when an item in this AdapterView has been selected
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int position, long id) { 
        // TODO Auto-generated method stub
               
      }

      @Override
      public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

      }

});

onItemSelected gives us a selected position of the spinner.

That’s it. Happy Coding 🙂

Reference:-

https://developer.android.com/guide/topics/ui/controls/spinner#java

Migrate an Existing Project to AndroidX

AndroidX is an open-source project by Google that provides a major improvement to the original Android Support Library. AndroidX is replaced the Support Library. Like support library, Google keeps AndroidX is independently from the Android OS and provides backward-compatibility across Android releases. AndroidX package structure is to encourage smaller and more focused libraries.

AndroidX replaces the original support library APIs with packages in the androidx namespace. Only the package and import names changed. Class, method, and field names did not change in migration.

Example:-

android.support.v7.widget.RecyclerView is changed to androidx.recyclerview.widget.RecyclerView

android.support.v7 is replced by androidx.

Migrating existing project:-

Before start migration, we need to make sure to follow the below things:-

1.  Android studio version should be higher than 3.2, You can check your android studio version from About Android Studio section. also use the latest Gradle version. Check project level Build.Gradle file to change the version.

2. Target SDK version and Compile SDK version should be 28 or greater. Check your app level Build.Gradle file to change target and compile SDK version.

3. Take a backup of your project. 

4. Add below properties to gradle.properties file. You can find this file on Project Level.

android.useAndroidX=true
android.enableJetifier=true

A.) android.useAndroidX: set to true, the Android plugin uses the AndroidX library instead of a Support Library. The value is false by default.

B.) android.enableJetifier: set to true, the Android plugin automatically migrates existing third-party libraries to use AndroidX. The value is false by default.

Let’s start migration:-

1.  Click Refactor from the menu in Android studio.

2. Then Click on Migrate to AndroidX from Refactor dropdown.

3. After that, It will ask you to take a backup of the whole project. If you have already taken the backup then ignore this step.

4. After the backup process clicks on Migrate, It will show list all support library where we are using in this project. Just click on Do Refactor and wait for some time.

5. After some time, you can see the project all support library replaced by the AndroidX library. Most of the support library will merge automatically and few we need to replaced manually. If you found any error,  Fix it manually. and test your app carefully. The application could crash due to incorrect auto-correction during migration.

That’s it. Enjoy Coding using AndroidX. 🙂

Reference:-

https://developer.android.com/jetpack/androidx/migrate

How to create Gridview using Recylerview Android

First let’s understand what Gridview and Recylerview are, in Android.

Gridview

A view that shows items in two-dimensional scrolling grid is known as Gridview. GridView layout in one of the most useful layouts in android to create a scrolling grid (rows & columns).

Recylerview

Recylerview is introduced in Android 5.0 Lollipop. The Recylerview widget is a more advanced and flexible version of Listview. It is a container used to display a large number of data sets that can be scrolled very efficiently by maintaining a limited number of views.

Now let’s start implementing Gridview

First, we need to add below dependency in build.gradle file at app level module.

dependencies {
      implementation 'com.android.support:recyclerview-v7:28.0.0'
}

After that, we need to add Recylerview widget in your main XML file.

<android.support.v7.widget.RecyclerView
         android:id="@+id/recyclerView"
         android:layout_width="match_parent"
         android:layout_height="wrap_content" />

Now we need to create item_logo.xml for Gridview row item.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/root"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:orientation="vertical">

    <ImageView
         android:id="@+id/ivLogo"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:scaleType="centerInside"
    />

</LinearLayout>

We need to create Adapter Object. An adapter in Android carries the data from a source (e.g. List<> ) and delivers it to a layout (.xml file).  The Adapter provides access to the data items.

public class LogoGridAdapter extends RecyclerView.Adapter<LogoGridAdapter.ViewHolder> {

    private List<Logo> logoList;
    private Context mContext;


    public LogoGridAdapter(Context mContext, List<Logo> logoList) {

        this.mContext = mContext;
        this.logoList = logoList;

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_logo, null));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        Logo logo = getLogo(position);

        if(logo.getLogoUrl() != null) {
            ImageUtils.displayImage(logo.getLogoUrl(), holder.ivLogo, ContextCompat.getDrawable(mContext, R.drawable.image_placeholder));
        }

    }


    private Logo getLogo(int position) {
        return logoList.get(position);
    }

    public List<Logo> getLogoList() {
        return logoList;
    }

    @Override
    public int getItemCount() {
        return logoList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
       
        LinearLayout root;
        ImageView ivLogo;

        public ViewHolder(View itemView) {
            super(itemView);
            // get logo view 
            ivLogo = (ImageView)itemView.findViewById(R.id.ivLogo);
            root =  (LinearLayout)itemView.findViewById(R.id.root);
        }
    }
}

To display images we can use Glide dependency.

Glide.with(imageView.getContext()).load(imageUrl)
                .apply(new RequestOptions().placeholder(placeHolder).dontAnimate().diskCacheStrategy(DiskCacheStrategy.ALL))
                .into(imageView);

Now we need to set data into Adapter.

LogoGridAdapter mLogoGridAdapter = new LogoGridAdapter(this, logoList);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
recyclerView.setAdapter(mLogoGridAdapter);

GridLayoutManager is a Recylerview Layout Manager implementation to lay out items in a grid.

In the above code “3” is a number of columns in per row.

Output

 

 

 

 

 

 

 

 

 

 

That’s it, Happy Coding 🙂

Reference:-  https://developer.android.com/guide/topics/ui/layout/recyclerview