Friday, 22 December 2017

Simple example of SeekBarPreference in Android

There is no predefined SeekBarPreference in Android. But we can make our own SeekBarPreference very simply. Here is simple example of making and using SeekBarPreference in Android.

SeekBarPreference.java
  
public class SeekBarPreference extends Preference implements SeekBar.OnSeekBarChangeListener {
    private TextView textValue;

    public SeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public SeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public SeekBarPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SeekBarPreference(Context context) {
        super(context);
    }

    @Override
    protected View onCreateView(ViewGroup parent) {
        super.onCreateView(parent);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.seekbar, parent, false);
        textValue = view.findViewById(R.id.textValue);
        TextView textTitle = view.findViewById(R.id.textTitle);
        textTitle.setText(getTitle());
        SeekBar seekBar = view.findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(this);

        SharedPreferences preferences = getSharedPreferences();
        int value = preferences.getInt(getKey(), 0);
        textValue.setText(String.format(Locale.getDefault(), "%d", value));
        seekBar.setProgress(value);
        return view;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        textValue.setText(String.format(Locale.getDefault(), "%d", i));
        SharedPreferences.Editor editor = getEditor();
        editor.putInt(getKey(), i);
        editor.apply();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
seekbar.xml
  
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="match_parent"
    android:paddingBottom="5dp"
    android:paddingTop="5dp">

    <TextView
        android:id="@+id/textTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:textColor="#000"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textTitle" />

    <TextView
        android:id="@+id/textValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="10dp"
        android:textColor="#000"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/seekBar" />
</android.support.constraint.ConstraintLayout>

Here is the settings.xml used in SettingsActivityFragment.
  
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.guna.testapplication.widgets.SeekBarPreference
        android:defaultValue="50"
        android:key="seekBar"
        android:title="Seek Bar" />
</PreferenceScreen>
SettingsActivity.java
 
public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

}
SettingsActivityFragment.java
 
public class SettingsActivityFragment extends PreferenceFragment {

    public SettingsActivityFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
}

Here is the full video tutorial


Interesting right?


If you are really interested in this code, then please share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You


Wednesday, 20 December 2017

Simple example of Using JobScheduler in Android

JobScheduler is the Android framework API for scheduling tasks or work. It first became available in Android 5.0 (API level 21), and remains under active development. Notably, Android 7.0 (API level 24) added the ability to trigger jobs based on ContentProvider changes.

If your app targets Android 5.0 (API level 21), we recommend that you use the JobScheduler to execute background tasks.

Here is the simple example of Scheduling and Cancelling the scheduled job. MainActivity.java
  
public class MainActivity extends AppCompatActivity {

    int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    public void addJob(View view) {
        count++;
        JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        ComponentName componentName = new ComponentName(this, MyJobService.class);
        JobInfo.Builder builder = new JobInfo.Builder(count, componentName);
        builder.setMinimumLatency(15000);//Start after 15 seconds
        PersistableBundle bundle = new PersistableBundle();
        bundle.putString("Title", "Job " + count);
        builder.setExtras(bundle);
        if (scheduler != null) {
            int result = scheduler.schedule(builder.build());
            if (result == JobScheduler.RESULT_SUCCESS) {
                showToast("Job scheduled successfully");
            } else {
                showToast("Job scheduling failed");
            }
        }
    }

    private void showToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
    }

    public void allJobs(View view) {
        startActivity(new Intent(this, AllJobsActivity.class));
    }
}


content_main.xml
  
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="@layout/activity_main">

    <Button
        android:id="@+id/buttonAddJob"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="addJob"
        android:text="Add Job"
        app:layout_constraintBottom_toTopOf="@id/buttonShowAllJob"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonShowAllJob"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="allJobs"
        android:text="All Jobs"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/buttonAddJob" />
</android.support.constraint.ConstraintLayout>


MyJobService.java
public class MyJobService extends JobService {
    private static final String TAG = MyJobService.class.getSimpleName();

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        PersistableBundle bundle = jobParameters.getExtras();
        Log.v(TAG, bundle.getString("Title") + " started");
        jobFinished(jobParameters, false);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        Log.v(TAG, "Job completed");
        return true;
    }
}
MyJobService should be registered in manifest as below.
<service
    android:name=".MyJobService"
    android:permission="android.permission.BIND_JOB_SERVICE" />
MyJobService.java
public class AllJobsActivity extends AppCompatActivity {

    private List<JobInfo> pendingJobs = null;
    private JobsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_jobs);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        RecyclerView recyclerView = findViewById(R.id.myJobList);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        final JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        if (scheduler != null) {
            pendingJobs = scheduler.getAllPendingJobs();
            adapter = new JobsAdapter(pendingJobs);
            recyclerView.setAdapter(adapter);
        }

        ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AllJobsActivity.this);
                builder.setTitle("Cancel Job");
                builder.setMessage("Are you sure to cancel this Job");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        JobInfo info = pendingJobs.get(viewHolder.getAdapterPosition());
                        scheduler.cancel(info.getId());
                        pendingJobs.remove(viewHolder.getAdapterPosition());
                        dialogInterface.dismiss();
                        adapter.notifyDataSetChanged();
                    }
                });
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        adapter.notifyDataSetChanged();
                    }
                });
                builder.create().show();
            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                View view = viewHolder.itemView;
                Paint p = new Paint();
                p.setColor(Color.RED);
                RectF rectF;
                if (dX > 0) {
                    rectF = new RectF(view.getLeft(), view.getTop(), dX, view.getBottom());
                } else {
                    rectF = new RectF(view.getRight() + dX, view.getTop(), view.getRight(), view.getBottom());
                }
                c.drawRect(rectF, p);
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        };
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

}
JobsAdapter.java
public class JobsAdapter extends RecyclerView.Adapter {
    private List pendingJobs;

    public JobsAdapter(List pendingJobs) {
        this.pendingJobs = pendingJobs;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.bind(position);
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView textView;

        ViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.text);
        }

        void bind(int position) {
            JobInfo info = pendingJobs.get(position);
            PersistableBundle bundle = info.getExtras();
            textView.setText(bundle.get("Title").toString());
        }
    }
}

Here is the full video tutorial


Interesting right?


If you are really interested in this code, then please share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You


Tuesday, 5 December 2017

Simple example of using ViewPager in Kotlin | Android

Though Kotlin has lot of massive features to speedup the development time, here is the simple example of using ViewPager in Android. In Kotlin we don't need to declare and initialize Views. We can simply access the id of Views from xml.

Ex:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.guna.kotlinapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
MainActivity.kt
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        setupViewPager(pager)
        tabs.setupWithViewPager(pager)
    }

    private fun setupViewPager(pager: ViewPager?) {
        val adapter = Adapter(supportFragmentManager)

        val f1 = BlankFragment.newInstance("One")
        adapter.addFragment(f1, "TAB 1")

        val f2 = BlankFragment.newInstance("Two")
        adapter.addFragment(f2, "TAB 2")

        val f3 = BlankFragment.newInstance("Three")
        adapter.addFragment(f3, "TAB 3")

        pager?.adapter = adapter
    }

    private class Adapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
        val fragments = ArrayList()
        val titles = ArrayList()
        override fun getItem(position: Int): Fragment = fragments.get(position)

        override fun getCount(): Int = fragments.size

        override fun getPageTitle(position: Int): CharSequence? = titles.get(position)

        fun addFragment(fragment: Fragment, title: String) {
            fragments.add(fragment)
            titles.add(title)
        }
    }
}
BlankFragment.kt
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_blank.view.*

class BlankFragment : Fragment() {
    var text = ""

    companion object {
        fun newInstance(text: String): BlankFragment {
            val fragment = BlankFragment()
            val bundle = Bundle()
            bundle.putString("Text", text)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        text = arguments?.get("Text").toString()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_blank, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.textView.setText(text)
    }
}

Did you noticed, we never declare pager nor initialized, instead we directly accessed it from activity_main.
In BlankFragment also, we didn't declare and initialize textView

And also, unless Java, default constructor will come with class name itself; like Adapter(manager: FragmentManager).

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then please share this post with your friends.


Simple example of using RecyclerView in Kotlin | Android

Simple example of using Spinner in Kotlin | Android

Simple example of using CheckBox in Kotlin | Android

Using Button in Kotlin | Android

Getting Started on Kotlin

Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 30 November 2017

Simple example of using RecyclerView in Kotlin | Android

Though Kotlin has lot of massive features to speedup the development time, here is the simple example of using RecyclerView in Android. In Kotlin we don't need to declare and initialize RecyclerView. We can simply access the id of RecyclerView from xml.

Ex :
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.guna.kotlinapplication.MainActivity">

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


We can simply access id of RecyclerView from above xml in kotlin file.
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = Adapter(myStrings, this)

Here is the Adapter.kt class.
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item.view.*

/**
 * Created by Guna on 30-11-2017.
 */
class Adapter(val strings: Array<String>, val activity: MainActivity) : RecyclerView.Adapter<Adapter.ViewHolder>() {

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        holder?.bind(strings[position], activity)
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder =
            ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item, parent, false))

    override fun getItemCount(): Int = strings.size

    class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
        fun bind(string: String, activity: MainActivity) {
            itemView.textView.setText(string)
            itemView.setOnClickListener{
                view ->  activity.fromAdapter(string)
            }
        }
    }
}

And Here is the MainActivity.kt class.
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    val myStrings = arrayOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
            "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen")
    val paint = Paint()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.setHasFixedSize(true)
        recyclerView.adapter = Adapter(myStrings, this)

        val callback = object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
            override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
                val fromPosition = viewHolder!!.adapterPosition
                val toPosition = target!!.adapterPosition

                val fromString = myStrings[fromPosition]
                val toString = myStrings[toPosition]

                myStrings[fromPosition] = toString
                myStrings[toPosition] = fromString
                recyclerView?.adapter?.notifyItemMoved(fromPosition, toPosition)
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
                if (direction == ItemTouchHelper.LEFT) {
                    Toast.makeText(this@MainActivity, myStrings[viewHolder!!.adapterPosition] + " Left Swiped", LENGTH_LONG).show()
                } else if (direction == ItemTouchHelper.RIGHT) {
                    Toast.makeText(this@MainActivity, myStrings[viewHolder!!.adapterPosition] + " Right Swiped", LENGTH_LONG).show()
                }
                recyclerView.adapter.notifyDataSetChanged()
            }

            override fun onChildDraw(c: Canvas?, recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
                if (dX > 0) {
                    paint.color = Color.GREEN
                    val rect = Rect(viewHolder!!.itemView!!.left, viewHolder.itemView.top, dX.toInt(), viewHolder.itemView.bottom)
                    c?.drawRect(rect, paint)
                } else if (dX < 0) {
                    paint.color = Color.RED
                    val rect = Rect(viewHolder!!.itemView.right.plus(dX).toInt(), viewHolder.itemView.top, viewHolder.itemView.right, viewHolder.itemView.bottom)
                    c?.drawRect(rect, paint)
                }
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
            }
        }

        val helper = ItemTouchHelper(callback)
        helper.attachToRecyclerView(recyclerView)
    }

    fun fromAdapter(string: String) {
        Toast.makeText(this, string, LENGTH_LONG).show()
    }
}

Did you noticed, we never declare recyclerView nor initialized, instead we directly accessed it from activity_main.
In ViewHolder also, we didn't declare and initialize textView

And also, unless Java, default constructor will come with class name itself; like Adapter(val strings: Array, val activity: MainActivity).

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then please share this post with your friends.


Simple example of using Spinner in Kotlin | Android

Simple example of using CheckBox in Kotlin | Android

Using Button in Kotlin | Android

Getting Started on Kotlin

Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Tuesday, 28 November 2017

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml.

Ex :
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.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //String array.
        val myStrings = arrayOf("One", "Two", "Three", "Four", "Five")
        
        //Adapter for spinner
        mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, myStrings)
        
        //item selected listener for spinner
        mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                Toast.makeText(this@MainActivity, myStrings[p2], LENGTH_LONG).show()
            }

        }
    }
}

Did you noticed, we never declare myCheckBox nor initialized, instead we directly accessed it from activity_main.
And also there is no new keyword while ArrayAdapter or implementing OnItemSelectedListener.

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Simple example of using CheckBox in Kotlin | Android


Using Button in Kotlin | Android


Getting Started on Kotlin


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Monday, 27 November 2017

Simple example of using CheckBox in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Button in Android. In Kotlin we don't need to declare and initialize CheckBox. We simply access the id of CheckBox from Kotlin file.

Ex :
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myCheckBox.setOnCheckedChangeListener { view, isChecked ->
            Toast.makeText(this, isChecked.toString(), LENGTH_LONG).show()
        }
    }
}

Did you noticed, we never declare myCheckBox nor initialized, instead we directly accessed it from activity_main.
And inside setOnCheckedChangeListener method, we didn't implement `onCheckedChanged` interface.

So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current Activity is java, don't worry, you can create your next Activity in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.

Here is the full video tutorial

Interesting right?


If you are really interested in this code, then share this post with your friends.


Using Button in Kotlin | Android


Getting Started on Kotlin


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You



Thursday, 16 November 2017

Basic data types of KOTLIN and simple examples.

In this section we describe the basic types used in Kotlin: numbers, characters, booleans, arrays, and strings.

Numbers

Kotlin handles numbers in a way close to Java, but not exactly the same. For example, there are no implicit widening conversions for numbers, and literals are slightly different in some cases.

Kotlin provides the following built-in types representing numbers (this is close to Java):

Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8


We can declare data types in KOTLIN as following way.
var a: Int = 0 //int var, we can reassign at runtime or anywhere in the code. 
val a:Int =0 //int val, val cannot reassign.
var a = 0 //int var
val a = 0 //int val

var a = 10.10 //Double
var a = 10.10f //Float
var a = 10.10F //Float

var a = 10L //Long

//You can use underscores to make number constants more readable:
val oneMillion=1_000_000

Every number type supports the following conversions:

toByte(): Byte

toShort(): Short

toInt(): Int

toLong(): Long

toFloat(): Float

toDouble(): Double

toChar(): Char

Operations


Here is the complete list of bitwise operations (available for Int and Long only):
  1. shl(bits) – signed shift left (Java's <<)
  2. shr(bits) – signed shift right (Java's >>)
  3. ushr(bits) – unsigned shift right (Java's >>>)
  4. and(bits) – bitwise and
  5. or(bits) – bitwise or
  6. xor(bits) – bitwise xor
  7. inv() – bitwise inversion

Ex:

var x = 1 shl 2
var x = 1 shr 2
var x = 1 ushr 2
var x = 1 and 2
var x = 1 or 2
var x = 1 xor 2
var x = 1.inv()

Also we have int() instead of ++ and dec() instead of --.

Ex:

var x = a.inc()

Characters

Characters are represented by the type Char
var c = 'a'.

Booleans

The type Boolean represents booleans, and has two values: true and false.
var b = true

Strings

Strings are represented by the type String. Strings are immutable. var s = "Hello Kotlin"

Interesting right?


If you are really interested in this code, then share this post with your friends.


Text WhatsApp message to +91-99654 70689 To join Android Developers WhatsApp group.
Join WhatsApp group by this link
Thank You