Open top menu



Example:-Dialog Working With Fragment in Android?





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

    <
TextView
       
android:id="@+id/lbl_your_name"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Enter user name" />

    <
EditText
       
android:id="@+id/username"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:imeOptions="actionDone"
       
android:inputType="text" />

</
LinearLayout>


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:id="@+id/activity_main"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:paddingBottom="@dimen/activity_vertical_margin"
   
android:paddingLeft="@dimen/activity_horizontal_margin"
   
android:paddingRight="@dimen/activity_horizontal_margin"
   
android:paddingTop="@dimen/activity_vertical_margin"
   
tools:context="com.project.example.dialogwithfragment.MainActivity">


    <Button
       
android:text="showCustomFragment"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_alignParentTop="true"
       
android:layout_centerHorizontal="true"
       
android:layout_marginTop="88dp"
       
android:id="@+id/showCustomFragment" />

    <Button
       
android:text="showAlertDialogFragment"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_below="@+id/showCustomFragment"
       
android:layout_alignRight="@+id/showCustomFragment"
       
android:layout_alignEnd="@+id/showCustomFragment"
       
android:layout_marginTop="43dp"
       
android:id="@+id/showAlertDialogFragment"
       
android:layout_alignLeft="@+id/showCustomFragment"
       
android:layout_alignStart="@+id/showCustomFragment" />
</RelativeLayout>

 ..................................................................................................................................................................

AlertDialog.java
..................................................................................................................................................................
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;



public class AlertDialog_Fragment extends DialogFragment {
    @Override
   
public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                // set dialog icon
               
.setIcon(android.R.drawable.stat_notify_error)
                // set Dialog Title
               
.setTitle("Alert dialog fragment example")
                // Set Dialog Message
               
.setMessage("This is a message")

                // positive button
               
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "Pressed OK", Toast.LENGTH_SHORT).show();
                    }
                })
                // negative button
               
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "Cancel", Toast.LENGTH_SHORT).show();
                    }
                }).create();
    }
}

 ..................................................................................................................................................................

Dialog_Fragment.java
..................................................................................................................................................................


import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;



public class Dialog_Fragment  extends DialogFragment {
    @Override
   
public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                // set dialog icon
               
.setIcon(android.R.drawable.stat_notify_error)
                // set Dialog Title
               
.setTitle("Alert dialog fragment example")
                // Set Dialog Message
               
.setMessage("This is a message")

                // positive button
               
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "Pressed OK", Toast.LENGTH_SHORT).show();
                    }
                })
                // negative button
               
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getActivity(), "Cancel", Toast.LENGTH_SHORT).show();
                    }
                }).create();
    }
}

 ..................................................................................................................................................................


My_DialogFragment .java
..................................................................................................................................................................


import android.app.DialogFragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;



public class My_DialogFragment extends DialogFragment implements TextView.OnEditorActionListener {

    private EditText mEditText;




    public interface UserNameListener {
        void onFinishUserDialog(String user);
    }

    // Empty constructor required for DialogFragment
   
public My_DialogFragment() {

    }

    @Override
   
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_fragment, container);
        mEditText = (EditText) view.findViewById(R.id.username);

        // set this instance as callback for editor action
       
mEditText.setOnEditorActionListener(this);
        mEditText.requestFocus();
        getDialog().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        getDialog().setTitle("Please enter username");

        return view;
    }

    @Override
   
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // Return input text to activity
       
UserNameListener activity = (UserNameListener) getActivity();
        activity.onFinishUserDialog(mEditText.getText().toString());
        this.dismiss();
        return true;
    }
}
 ..................................................................................................................................................................


MainActivity .java
..................................................................................................................................................................



import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener, My_DialogFragment.UserNameListener {

    @Override
   
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn= (Button)findViewById(R.id.showCustomFragment);
        btn.setOnClickListener(this);
        Button btn1= (Button)findViewById(R.id.showAlertDialogFragment);
        btn1.setOnClickListener(this);
    }

    @Override
   
public void onFinishUserDialog(String user) {
        Toast.makeText(this, "Hi, " + user, Toast.LENGTH_SHORT).show();     }

    public void onClick(View view) {
        // close existing dialog fragments
       
FragmentManager manager = getFragmentManager();
        Fragment frag = manager.findFragmentByTag("fragment_edit_name");
        if (frag != null) {
            manager.beginTransaction().remove(frag).commit();
        }
        switch (view.getId()) {
            case R.id.showCustomFragment:
                My_DialogFragment editNameDialog = new My_DialogFragment();
                editNameDialog.show(manager, "fragment_edit_name");
                break;
            case R.id.showAlertDialogFragment:
                AlertDialog_Fragment alertDialogFragment = new AlertDialog_Fragment();
                alertDialogFragment.show(manager, "fragment_edit_name");
                break;
        }
    }
}





Read more








You need to remove or replaces some Special Character eg- Backslash (\n), [ , ’, and \n ,\u,\s, etc. You replaces some regular expressions are complicated things,

String str="hello, who are \u you";
 
Step 1- The (\u )escape character replace very complicated.

String value=str. replaceAll(Pattern.quote("\\u") , "new String value");
 
 
Step 2- the replace  all digit Value from String.

String str="hello, who are 24314 you ";

String something=str.replaceAll(
"[\\p{Digit}]", "");

Output:-hello who are you

Step 3- The replace  all regular expression from String.

String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll(
"[^a-zA-Z0-9]+","");
 
 Or equivalent

String alphaOnly = input.replaceAll(
"[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll(
"[^\\p{Alpha}\\p{Digit}]+","");









 thank you  
Read more


Android- How to get Rgb Color programmaticall.



 Get the pixel in height And width when touch on imageView.


activity_main.xml
...................................................................................................................................................................
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"
   
android:orientation="vertical">

            android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Android Beginner tutorial point"
       
tools:context=".MainActivity"
       
android:textSize="40dp"
       
android:textStyle="bold"
 
   
        android:id="@+id/colorAvarage"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="touched color: "/>
            android:id="@+id/image"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:src="@drawable/multicolor"
       
android:layout_marginTop="40dp"/>





...................................................................................................................................................................

 MainActivity.java
...................................................................................................................................................................



import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;

public class  MainActivit extends Activity {

    TextView touchedXY, invertedXY, imgSize, colorRGB;
    ImageView imgSource;

    @Override
   
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.color_code_activity);

        touchedXY = (TextView)findViewById(R.id.TutorialBlog);
        colorRGB = (TextView)findViewById(R.id.colorAvarage);
        imgSource = (ImageView)findViewById(R.id.image);
        imgSource.setOnTouchListener(imgOnTouchListener);

             }

        OnTouchListener imgOnTouchListener = new OnTouchListener(){

        @Override
       
public boolean onTouch(View view, MotionEvent event) {

            float eventX = event.getX();
            float eventY = event.getY();
            float[] eventXY = new float[] {eventX, eventY};

            Matrix invertMatrix = new Matrix();
            ((ImageView)view).getImageMatrix().invert(invertMatrix);

            invertMatrix.mapPoints(eventXY);
            int x = Integer.valueOf((int)eventXY[0]);
            int y = Integer.valueOf((int)eventXY[1]);

                        Drawable imgDrawable = ((ImageView)view).getDrawable();
            Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();

            //Limit x, y range within bitmap

            
if(x < 0){
                x = 0;
            }else if(x > bitmap.getWidth()-1){
                x = bitmap.getWidth()-1;
            }

            if(y < 0){
                y = 0;
            }else if(y > bitmap.getHeight()-1){
                y = bitmap.getHeight()-1;
            }

            int touchedRGB = bitmap.getPixel(x, y);
            colorRGB.setText("Color Code In Hexa------->   " + "#" +    Integer.toHexString(touchedRGB));
            colorRGB.setTextColor(touchedRGB);
            touchedXY.setTextColor(touchedRGB);
            return true;
        }};

}
...................................................................................................................................................................


Read more

 Android- Explain how to get Color code from Image programmatically.

First Set Image in Bitmap :-
final Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
 
Then Get Touch X and Y coordinate from ImageView.
public boolean onTouch(View v, MotionEvent event) {

    x = (int)event.getX();

    y= (int)event.getY();

    return false;

}
 
Get the color code in Hex String touch on imageView.
Integer.toHexString(bitmap.getPixel(x, y);
 
Get the color code in Hex String touch on imageView.

activity_main.xml
.............................................................................................................................................................

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"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_main"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical">



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Android Beginner point"

        android:textSize="25dp"

        android:textStyle="bold"

        android:id="@+id/textView" />



    <ImageView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:src="@drawable/multicolor"

        android:layout_below="@+id/textView"

        android:layout_toRightOf="@+id/textView"

        android:layout_toEndOf="@+id/textView"

        android:id="@+id/imageView" />



</LinearLayout>

.............................................................................................................................................................

MAinActivity.java
.............................................................................................................................................................
import android.graphics.Bitmap;

import android.graphics.drawable.BitmapDrawable;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.MotionEvent;

import android.view.View;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;



public class MainActivity extends AppCompatActivity {

     int x,y;

    TextView txtView;

    ColorUtils utils=new ColorUtils();

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        txtView=(TextView)findViewById(R.id.textView);

        ImageView imageView=(ImageView)findViewById(R.id.imageView);

        final Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

         imageView.setOnTouchListener(new View.OnTouchListener() {

             @Override

             public boolean onTouch(View v, MotionEvent event) {

                 x = (int)event.getX();

                 y= (int)event.getY();

                 int pixel = bitmap.getPixel(x,y);

                 txtView.setTextColor(bitmap.getPixel( x,y));

                   Toast.makeText(getApplicationContext(),"#"+Integer.toHexString(bitmap.getPixel(x, y)),Toast.LENGTH_LONG).show();



                 return false;

             }

         });



    }

}
 .............................................................................................................................................................


 


Read more





Example- Explain how to ON and OFF Flash Light in android device programmatically.

Step 1- Add below permission in manifest file.

<uses-permission android:name="android.permission.CAMERA" />
<
uses-feature android:name="android.hardware.camera" />

.............................................................................................

activity_main.xml
.............................................................................................

<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"
    android:background="@drawable/gradient"
    tools:context=".MainActivity" >

    <ImageButton
       
android:id="@+id/btnSwitch"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dip"
        android:src="@drawable/switch_on_icon"
        android:background="@null"
        android:scaleType="fitXY"
        android:contentDescription="@null"
        />
</RelativeLayout>


.............................................................................................

MainActivity.Java
.............................................................................................

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends AppCompatActivity {
    ImageButton btnSwitch;

    private Camera camera;
    private boolean isFlashOn;
    private boolean hasFlash;
    Parameters params;
    MediaPlayer mp;

    @Override
   
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

        
        hasFlash = getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        if (!hasFlash) {

            AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
            alert.setTitle("Error");
            alert.setMessage("device doesn't support flash light!");
            alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alert.show();
            return;
        }
       
        getCamera();
       
        toggleButtonImage();
       
        btnSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
           
public void onClick(View v) {
                if (isFlashOn) {
                    turnOffFlash();
                } else {
                    turnOnFlash();
                }
            }
        });
    }
    private void getCamera() {
        if (camera == null) {
            try {
                camera = Camera.open();
                params = camera.getParameters();
            } catch (RuntimeException e) {

            }
        }
    }
   
    private void turnOnFlash() {
        if (!isFlashOn) {
            btnSwitch.setBackgroundResource(R.drawable.switch_on_icon);
            if (camera == null || params == null) {
                return;
            }
           
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
            isFlashOn = true;
            toggleButtonImage();
        }

    }
   
    private void turnOffFlash() {
        if (isFlashOn) {
            if (camera == null || params == null) {
                return;
            }
            params = camera.getParameters();
            params.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
            isFlashOn = false;
            toggleButtonImage();
        }
    }
   
    private void toggleButtonImage(){
        if(isFlashOn){
            btnSwitch.setImageResource(R.drawable.switch_on_icon);
        }else{
            btnSwitch.setImageResource(R.drawable.switch_off_icon);
        }
    }

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

    @Override
   
protected void onPause() {
        super.onPause();
        turnOffFlash();
    }

    @Override
   
protected void onRestart() {
        super.onRestart();
    }

     

    @Override
   
protected void onStart() {
        super.onStart();
        getCamera();
    }

    @Override
   
protected void onStop() {
        super.onStop();
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }
}

 ............................................................................................




Read more