Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. Show all posts

Sunday, 11 June 2017

How To Edit Textview in Android

How To Edit Textview in Android
In activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="25sp"
        android:textStyle="bold"
        android:gravity="center" />
</LinearLayout>

In MainActivity.java.
package com.mahesh.androidissimples.textviewtoedit;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textview;
    AlertDialog alertDialog;
    EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textview= (TextView) findViewById(R.id.textview);
        alertDialog=new AlertDialog.Builder(this).create();

        editText=new EditText(this);
        alertDialog.setTitle("Edit the text");
        alertDialog.setView(editText);
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "SAVE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                textview.setText(editText.getText());
            }
        });
        textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText(textview.getText());
                alertDialog.show();
            }
        });
    }
}


Output



Android Settings Tutorial using PreferenceFragment

                        Android Settings Tutorial using PreferenceFragment
First add dependencies in build.gradle

compile 'com.android.support:preference-v7:25.3.1'

Create xml directory under res folder under xml folder. create xml folder name is preferences.

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<SwitchPreference
    android:defaultValue="true"
    android:key="updateNotification"
    android:summary="Remind you to update"
    android:title="Update"
    />

    <ListPreference
        android:defaultValue="1"
        android:entries="@array/listArray"
        android:entryValues="@array/listValueforSharedPreference"
        android:key="languageListSetting"
        android:summary="Select any language"
        android:title="Language"
        />
</PreferenceScreen>

Create a new layout file under value folder. array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="listArray">
        <item>English</item>
        <item>Hindi</item>
    </string-array>
    <string-array name="listValueforSharedPreference">
        <item>1</item>
        <item>2</item>
    </string-array>
</resources>

Create a new Class and extends with PreferenceFragment and imlements OnSharedPreferenceChangeListener

package com.mahesh.androidissimples.setting;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.widget.Toast;




/**
 * A simple {@link Fragment} subclass.
 */
public class SettingFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
    public static final String KEY_LANGUAGE="languageListSetting";
    public static final String KEY_SETTINGS_MENU="updateNotification";
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getPreferenceManager().setSharedPreferencesName("SettingPrf");
        getPreferenceManager().setSharedPreferencesMode(Context.MODE_PRIVATE);

        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals(KEY_LANGUAGE)){
            Toast.makeText(getActivity(), "Changed Language", Toast.LENGTH_SHORT).show();
        }
        if (key.equals(KEY_SETTINGS_MENU)){
            Toast.makeText(getActivity(), "Changed Settings menu", Toast.LENGTH_SHORT).show();
        }
    }
}

In MainActivity class

package com.mahesh.androidissimples.setting;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getFragmentManager().beginTransaction().replace(android.R.id.content,new SettingFragment())
                .commit();
    }
}

Output:

 

Sunday, 21 May 2017

Android ProgressBar

Android ProgressBar

We can display the android progress bar dialog box to dislay the status of work being done e.g. downloading file, analyzing status of work etc.

Here, I am going to display the progress dialog for dummy file download operation.

Here I am using android.ap.ProgressDialog class to show the progress bar, Android ProgressDialog is the subclass of AlertDialog class.

The ProgressDialog class provides method to work on progress bar like setProgress(), setMessage(), setProgressStyle(), show() etc. The progress range of Progress Dialog Is 0 to 10000.

How to define ProgressDialog

ProgressDialog progressBar=new ProgressDialog(this);

progressBar.setCancelable(true); //you can cancel it by pressing back button

progressBar.setMessage(“File downloading…”);

progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

progressBar.setProgress(0); //initially progress is 0

progressBar.setMax(100); //set the maximum value 100

progressBar.show();//dislay the progress bar


Android TimePicker

Android TimePicker

Android TimePicker widget is used to select date.It allows you to select time by hour and minute. You cannot select time by seconds.

The android.widget.TimePicker is the subclass f FrameLayout class.

Android TimePicker Example

Activity_main.xml

File:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mahesh.androidissimples.timepickerdemo.MainActivity">

   <TimePicker
       android:id="@+id/timePicker"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="50dp"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/timePicker"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:text="Current Time:"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/timePicker"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="37dp"
        android:text="Change Time"
        android:layout_marginTop="20dp"/>

</RelativeLayout>

Activity Class

File:MainActivity.class

package com.mahesh.androidissimples.timepickerdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    TimePicker timePicker;
    Button changetime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        textView= (TextView) findViewById(R.id.textView);
        timePicker= (TimePicker) findViewById(R.id.timePicker);
       
        changetime= (Button) findViewById(R.id.button);
        textView.setText(getCurrentTime());
        changetime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText(getCurrentTime());
            }
        });
    }

    private String getCurrentTime() {
        String currentTime="Current Time:"+timePicker.getCurrentHour()+":"+timePicker.getCurrentMinute();
        return currentTime;
    }
}

Output:




Android SeekBar

Andriod SeekBar

Android SeekBar is a kind of ProgressBar With draggable thumb. The end user can drag the thum left and right to move the progress of song, file download etc.

The SeekBar.OnSeekBarChangeListener interface provides mthods to perform even handling for seek bar.

Android SeekBar and RatingBar classes are the sub classes of AbsSeekBar.

Android SeekBar Example

activity_main.xml

File:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mahesh.androidissimples.seekbardemo.MainActivity">

    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="39dp"/>

</RelativeLayout>

Activity class
File:MainActivity.class
package com.mahesh.androidissimples.seekbardemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
    SeekBar seekBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        seekBar= (SeekBar) findViewById(R.id.seekBar1);
        seekBar.setOnSeekBarChangeListener(this);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Toast.makeText(this, "seekbar progress:"+progress, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        Toast.makeText(this,"seekbar touch started!",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Toast.makeText(this, "seekbar touch stopped!", Toast.LENGTH_SHORT).show();

    }
}


Output:

Android WebView

Android WebView

Android WebView is used to display web page in android. The web page can be loaded from same application or URL. It is used to display online content in android activity.

Android Web View uses webkit engine to display web page.

The android.webkit.WebView is the subclass of AbsoluteLayout class.
The loadUrl() and loadData() method of Android WebView class are used to load and display web page.

Android WebView Example

activity_main.xml

File:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mahesh.androidissimples.webviewdemo.MainActivity">

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">

    </WebView>

</RelativeLayout>

Activity class

File:MainActivity.java

package com.mahesh.androidissimples.webviewdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView mywebview= (WebView) findViewById(R.id.webView1);

        mywebview.loadUrl("http://www.google.com");
    }

}

Activity and its Lifecycle

                                              Activity and its Lifecycle

What is an Activity?

Which present something to you with which you can interact there call Activity.An application component that provides a screen

What they do.

You can draw different type of UI on its windows.Every app has 1 main activity and other activities.An ap can start any Activity belonging to certain conditions.When a new Activity starts,the previous Activity is stopped and added to stack knows as BackStack.

What is a callback method?

Android OS calls certain method on your Activity class to notify whether your app is running currently or not.
Just like JVM calling public static void main

General guidelines

1.       Don’t do heavy processing or network consuming operations when user is currently away from your app.
2.       App should not crash when another app is started.
3.       Don’t lose the user’s progress or session data.

Activity Lifecycle Methods

When user launch your apps for the first time now the user can launch your app from the app section or he can launch through widget or whatever so what happen when the user click your app icon. These three methods are called onCreate (), onStart (), onResume ().What happens when the user actually try to pause your app. So in this case onPause (), onStop () method are called. What happens when the user click the back button. So in this case these methods are called onRestart (), onStart (), onResume () in a quick.

What is Logcat?

Logcat is used for debugging purposes. We will use the logcat in activity to check the Activity Lifecycle Method. Logcat Print different messages using android.util.Log class.

Log.d (String tag, String message)
Log.d (“LIFECYCLE”, ”onCreate was called”);

There are other method in Logcat
1.     For information we can use Log.i(String tag, String message)
2.     For Error we can use Log.e(String tag, String message)
3.     For warning we can use Log.w(String tag, String message)
4.     For Verbose we can use Log.v(String tag, String message)


Activity Lifecycle Diagram


Example:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Android is simples","onCreate was called");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Android is simples","onResume was called");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Android is simples","onStart was called");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Android is simples","onPause was called");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Android is simples","onStop was called");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Android is simples","onRestart was called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Android is simples","onDestroy was called");
    }
}