Wednesday 5 December 2018

Kotlin-Create TextView Programatically

Hello Friends,
      In this tutorial I am going create a textview dynamically in kotlin and add it to Linearlayout layout.

1. activity_main.xml: Following is the activity_main.xml containing the TextView with the text .

<?xml version="1.0" encoding="utf-8"?>  
 <android.support.constraint.ConstraintLayout xmlns:android="https://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=".TextViewSample">  
  <LinearLayout  
   android:id="@+id/ll_main_layout"  
   android:layout_width="match_parent"  
   android:layout_height="wrap_content"  
   android:orientation="vertical">  
   <TextView  
    android:id="@+id/tv_static"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:textSize="20sp"  
    android:padding="20sp"  
    android:justificationMode="inter_word"  
    android:text="This textview is created from xml"/>  
  </LinearLayout>  
 </android.support.constraint.ConstraintLayout>

2. Creation of textview dynamically,
val tv_programtically = TextView(this)
tv_programtically.textSize = 20f
tv_programtically.text = "This textview is an dynamic textview in kotlin"

3. Finally the complete code is:

  TextViewSample.kt
package com.android.developer.kotlinsample

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.TextView
class TextViewSample : AppCompatActivity() {

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

    /** Dynamic creation of text view */
    val tv_programtically = TextView(this)
    tv_programtically.textSize = 20f
    tv_programtically.text = "This textview is an dynamic textview in kotlin"
    /**------end--------**/

    // add TextView to LinearLayout
    val ll_main_layout = findViewById(R.id.ll_main_layout) as LinearLayout
    ll_main_layout.addView(tv_programtically)
  }
}
Hope this will help some one. Enjoy Coding.... :)

Kotlin-bind OnClickListener on view

Hello Friends,
 In this tutorial I am showing you how to bind the click listener on View in Kotlin.

1. Code snippet to set OnClickListener on Textview in Kotlin Android
val tvStatic = findViewById(R.id.tv_static) as TextView
tvStatic.setOnClickListener {
 // your code to perform when the user clicks on the TextView
 Toast.makeText(this, "You clicked on TextView 'Click Me'.", Toast.LENGTH_SHORT).show()
}

2. Code snippet to set OnClickListener on Button in Kotlin Android
// get reference to button
val btn_click = findViewById(R.id.btn_click_me) as Button
// set on-click listener
btn_click.setOnClickListener {
    Toast.makeText(this@MainActivity, "You clicked on Button.", Toast.LENGTH_SHORT).show()
}

3. Code snippet to set OnClickListener on ImageView in Kotlin Android
// get reference to ImageView
val iv_profile = findViewById(R.id.image_view) as ImageView
// set on-click listener for ImageView
iv_profile.setOnClickListener {
    // your code here
}

Hope this will help someone.
Enjoy Coding..... :)

Saturday 23 June 2018

Android Live Data Tutorial | Live Data | Data Binding | Architecture Components

Hello Friends,
              Today I am going to share me small tutorial of LiveData with Data Binding.

-What is LiveData?
     LiveData is an observable data holder class that can be observed within
     a given lifecycle. It lets the components in your app, usually the UI,
     observe LiveData objects for changes.

-The advantages of using LiveData

  •      Ensures your UI matches your data state
  •      No memory leaks
  •      No crashes due to stopped activities
  •      No more manual lifecycle handling
  •      Always up to date data
  •      Proper configuration changes
  •      Sharing resources
-How to use it in our app

   a. Add below dependency in app/build.gradle

implementation "android.arch.lifecycle:extensions:1.1.1" 


   
   b. UserViewModel.java : Creating a ViewModel class

package com.android.developer.livedatademo.model;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;

/**
 * Created by mukesh on 13/6/18.
 */
public class UserViewModel extends ViewModel {

    // Create a LiveData with a String
    private MutableLiveData mUser;

    public MutableLiveData getUser() {
        if (mUser == null) {
            mUser = new MutableLiveData();
        }
        return mUser;
    }
} 

In Activity class we creates an observer which updates the ui.
final Observer nameObserver = new Observer() {
      @Override
      public void onChanged(@Nullable final User user) {
      // Update the UI, in this case, a TextView.
      binding.tvUserName.setText(user.getName());
    }
};

Next step is observe the livedata, passing in the activity as a LifecycleOwner and the Observer.
userViewModel.getUser().observe(this, nameObserver);
binding.btnClick.setOnClickListener(this); 

The complete code,

package com.android.developer.livedatademo;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.android.developer.livedatademo.databinding.ActivityMainBinding;
import com.android.developer.livedatademo.model.User;
import com.android.developer.livedatademo.model.UserViewModel;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    UserViewModel userViewModel;
    ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        // Get the ViewModel.
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        // Create the observer which updates the UI.
        final Observer nameObserver = new Observer() {
            @Override
            public void onChanged(@Nullable final User user) {
                // Update the UI, in this case, a TextView.
                binding.tvUserName.setText(user.getName());
            }
        };

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        userViewModel.getUser().observe(this, nameObserver);
        binding.btnClick.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        User user = new User();
        user.setName("Mukesh Yadav");
        user.setAge("25");
        userViewModel.getUser().setValue(user);
    }
} 

Download the complete code here

Hope this will helps someone.
Enjoy Coding... :)

Sunday 17 December 2017

Android MVP for Beginners | Android MVP tutorial | Model-View-Presenter: Android | Android Architecture with MVP

Hello Friends,
          Today I am  going to share a very simple example of Android MVP.
In this sample I am using MVP pattern for network call and and user
form(login form) data validation which is mainly used in most of the android
application.

Model View Presenter divides application into three layers i.e: Model, View and Presenter.
  1. Model: This handles the data part of our application
  2. Presenter: It acts as a bridge that connects a Model and a View.
  3. View: This is responsible for laying out views with the relevant data as instructed by the Presenter     

Note: The View never communicates with Model directly

1. LoginActivity.java 
package android.developer.solutions.androidmvp.activity.login.view;

import android.content.Intent;
import android.developer.solutions.androidmvp.R;
import android.developer.solutions.androidmvp.activity.home.view.HomeActivity;
import android.developer.solutions.androidmvp.activity.login.interactor.LoginInteractorImpl;
import android.developer.solutions.androidmvp.activity.login.presenter.ILoginPresenter;
import android.developer.solutions.androidmvp.activity.login.presenter.LoginPresenterImpl;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class LoginActivity extends AppCompatActivity implements ILoginView {
    EditText username;
    EditText password;
    ProgressBar progress;
    Button button;
    private ILoginPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        progress = (ProgressBar) findViewById(R.id.progress);
        button = (Button) findViewById(R.id.btnLogin);
        password = (EditText) findViewById(R.id.password);
        username = (EditText) findViewById(R.id.username);
        presenter = new LoginPresenterImpl(this, new LoginInteractorImpl());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.validateCredentials(username.getText().toString(), password.getText().toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        presenter.onDestroy();
        super.onDestroy();
    }

    @Override
    public void showProgress() {
        progress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progress.setVisibility(View.GONE);
    }

    @Override
    public void setUsernameError() {
        username.setError("Invalid user name");
    }

    @Override
    public void setPasswordError() {
        password.setError("Invalid password");
    }

    @Override
    public void navigateToHome() {
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }
}


2. ILoginView.java

package android.developer.solutions.androidmvp.activity.login.view;

/**
 * Created by Mukesh on 12/16/2017.
 * androiddevelopersolutions.com
 */
public interface ILoginView {
    void showProgress();
    void hideProgress();
    void setUsernameError();
    void setPasswordError();
    void navigateToHome();
}


Download complete code from here

Hope this will helps some one.
Enjoy Coding............ :)

 

Copyright @ 2013 Android Developers Blog.