Wednesday 4 March 2015

Contextual Action Bar

The contextual action bar (CAB) is a temporary action bar that overlays your app's current action bar while data is selected. It appears after the user long-presses on a selectable data item.

From here the user can:
  • Select additional data items by touching them.
  • Trigger an action from the CAB that applies to all highlighted data items. The CAB then automatically dismisses itself.
  • Dismiss the CAB via the navigation bar's Back button or the CAB's checkmark button. This removes the CAB along with all selection highlights.
Create new menu item xml inside our res/menu/  folder.


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/item_delete"
        android:icon="@android:drawable/ic_menu_delete"
        android:showAsAction="ifRoom|withText"
        android:title="Delete"
        android:titleCondensed="Delete">
    </item>
</menu>

Write a code to start action mode in any event
For example:

listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
 @Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
// Capture total checked items
 final int checkedCount = listView.getCheckedItemCount();
// Set the CAB title according to total checked items
mode.setTitle(checkedCount + " Selected");
// Calls toggleSelection method from ListViewAdapter Class
adapter.toggleSelection(position);
}
 
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
 switch (item.getItemId()) {
case R.id.item_delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = adapter.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
Model selecteditem = adapter.getItem(selected.keyAt(i));
// Remove selected items following the ids
adapter.remove(selecteditem);
}
   }
   // Close CAB
  mode.finish();
  return true;
  default:
  return false;
}
}
  @Override
  public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.contextual_menu, menu);
return true;
}
 
@Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
adapter.removeSelection();
}
  @Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
});

To get full Code   Click Here

output:








Android Drag And Drop Example

Drag and Drop is one of the best feature provided by the Android Developer API. It can be used to drag data from a view and drop it in another view. In this Tutorial we are going to see how to implement Drag and Drop feature in a Android Application. In this we are going to count the total number of drops and number of successful drops.

Example:

main.xml:
<LinearLayout 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:gravity="center"
    android:orientation="vertical" >

    <LinearLayout

        android:id="@+id/bottomlinear"
        android:layout_width="match_parent"
        android:layout_height="400px"
        android:background="#00ff00"
        android:gravity="center"
        android:orientation="vertical" >

        <Button

            android:id="@+id/one"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Drag Me"
            android:textSize="30sp" />
    </LinearLayout>

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#29166f"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView

            android:id="@+id/drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Drop Here"
            android:textSize="30sp" />

        <TextView

            android:id="@+id/Total"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp" />

        <TextView

            android:id="@+id/Sucess"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp" />

        <TextView

            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp" />

        <TextView

            android:id="@+id/website"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </LinearLayout>

</LinearLayout>


DnDActivity:


import android.app.Activity;

import android.content.ClipData;
import android.content.Intent;
import android.os.Bundle;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DnDActivity extends Activity 
{
Button drag;
LinearLayout drop;
TextView text, sucess;
int total, failure = 0;
private TextView Website;
private TextView text_click;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
drag = (Button) findViewById(R.id.one);
drop = (LinearLayout) findViewById(R.id.bottomlinear);
text = (TextView) findViewById(R.id.Total);
sucess = (TextView) findViewById(R.id.Sucess);
Website = (TextView) findViewById(R.id.website);
text_click = (TextView) findViewById(R.id.text);
Website.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
      Intent i=new Intent(DnDActivity.this,SecondActivity.class);
         startActivity(i);
}
});
drop.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
// TODO Auto-generated method stub
final int action = event.getAction();
switch (action)
 {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DROP: {
failure = failure + 1;
return (true);
}
case DragEvent.ACTION_DRAG_ENDED: {
total = total + 1;
int suc = total - failure;
sucess.setText("Sucessful Drops :" + suc);
text.setText("Total Drops: " + total);
text_click.setText("Click on the Url");
Website.setText("http://saravananandroid.blogspot.in/");
return (true);
}
default:
break;
}
return true;
}
});
drag.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent arg1) {
// TODO Auto-generated method stub
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadow = new View.DragShadowBuilder(drag);
v.startDrag(data, shadow, null, 0);
return false;
}
});
}

}


activity_second.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="fill_parent"
    android:orientation="vertical" >
    <WebView
        android:id="@+id/webview01"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" >
    </WebView>
</LinearLayout>

SecondActivity.Java:


import android.app.Activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class SecondActivity extends Activity 
{
ProgressDialog mProgress;
WebView web;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
ProgressDialog ProgDialog;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
try {
web = (WebView) findViewById(R.id.webview01);
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectedToInternet();
// Asynchronous Task
if (isInternetPresent)
loadData();
else
AlertMessageDialog(SecondActivity.this,
"No Internet Connection", "Drag And Drop");

catch (Exception e) {
System.out.println(e);
}

}

public class myWebClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);

}


@Override

public boolean shouldOverrideUrlLoading(WebView view, String url)
                {
// TODO Auto-generated method stub
                        view.loadUrl(url);
return true;

}


@Override

public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub

super.onPageFinished(view, url);

if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
}

public void loadData() {

try {
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
mProgress = new ProgressDialog(SecondActivity.this);
mProgress.setMessage("Loading...");
mProgress.setIndeterminate(false);
mProgress.setCancelable(false);
mProgress.show();
web.loadUrl("http://saravananandroid.blogspot.in/");
} catch (Exception e) {
System.out.println(e);
}
}

// alert dialog

public void AlertMessageDialog(final Activity a, final String text,final String title)
 {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(a);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(text)
.setCancelable(false)
.setPositiveButton("Try Again",
   new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ProgDialog = new ProgressDialog(SecondActivity.this);
ProgDialog.setMessage("Fetching Connection...");
ProgDialog.setIndeterminate(false);
ProgDialog.setCancelable(false);
ProgDialog.show();
handler = new Handler();
handler.postDelayed(r, 5000);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}

Runnable r = new Runnable() {

@Override
public void run() {
ProgDialog.cancel();
isInternetPresent = cd.isConnectedToInternet();
// Asynchronous Task
if (isInternetPresent) {
handler.removeCallbacks(r);
loadData();
} else
AlertMessageDialog(SecondActivity.this,
"No Intenrnet Connection", "Drag And Drop");
}
};

}



ConnectionDetector.java:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
     
    private Context _context;
     
    public ConnectionDetector(Context context){
        this._context = context;
    }
    public boolean isConnectedToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) 
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) 
                  for (int i = 0; i < info.length; i++) 
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
          }
          return false;
    }
}

Result: