Showing posts with label toolbar in android. Show all posts
Showing posts with label toolbar in android. Show all posts

Friday, January 30, 2015

Spinner in Toolbar Example in Android

Step: 1
======
SpinToolbarActivity.java

package com.pratap.cardviews1;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.Toast;

public class SpinToolbarActivity extends AppCompatActivity {

private Toolbar toolbar;

private Spinner spinner_nav;

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

if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);

}
addItemsToSpinner();

}

// add items into spinner dynamically
public void addItemsToSpinner() {

ArrayList<String> list = new ArrayList<String>();
list.add("Top News");
list.add("Politics");
list.add("Business");
list.add("Sports");
list.add("Movies");

// Custom ArrayAdapter with spinner item layout to set popup background

CustomSpinnerAdapter spinAdapter = new CustomSpinnerAdapter(
getApplicationContext(), list);



// Default ArrayAdapter with default spinner item layout, getting some
// view rendering problem in lollypop device, need to test in other
// devices

/*
* ArrayAdapter<String> spinAdapter = new ArrayAdapter<String>(this,
* android.R.layout.simple_spinner_item, list);
* spinAdapter.setDropDownViewResource
* (android.R.layout.simple_spinner_dropdown_item);
*/

spinner_nav.setAdapter(spinAdapter);

spinner_nav.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
String item = adapter.getItemAtPosition(position).toString();

// Showing selected spinner item
Toast.makeText(getApplicationContext(), "Selected : " + item,
Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Settings Clicked",
Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search Clicked",
Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_add) {
Toast.makeText(getApplicationContext(), "Add Clicked",
Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_delete) {
Toast.makeText(getApplicationContext(), "Delete Clicked",
Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}


toolbar.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar 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/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
>

<Spinner
android:id="@+id/spinner_nav"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</android.support.v7.widget.Toolbar>

spintoolbaractivity.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"
android:background="#c9c9c9"
android:orientation="vertical" >

<include
android:id="@+id/toolbar"
layout="@layout/spintoolbar" />


</LinearLayout>


Step: 2
======
CustomSpinnerAdapter.java


package com.pratap.cardviews1;

import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

// Custom Adapter for Spinner
public class CustomSpinnerAdapter extends ArrayAdapter<String> {

private Context context1;
private ArrayList<String> data;
public Resources res;
LayoutInflater inflater;

public CustomSpinnerAdapter(Context context, ArrayList<String> objects) {
super(context, R.layout.spinner_row, objects);

context1 = context;
data = objects;

inflater = (LayoutInflater) context1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}

// This funtion called for each row ( Called data.size() times )
public View getCustomView(int position, View convertView, ViewGroup parent) {

View row = inflater.inflate(R.layout.spinner_row, parent, false);

TextView tvCategory = (TextView) row.findViewById(R.id.tvCategory);

tvCategory.setText(data.get(position).toString());

return row;
}
}



spinner_row.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/spinner_selector"
android:orientation="vertical" >

<TextView
android:id="@+id/tvCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textSize="18sp"
/>

</RelativeLayout>

values/styles.xml

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

<style name="AppTheme" parent="AppTheme.Base" />

<style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
<!-- your app branding color for the app bar -->
<item name="colorPrimary">@color/md_teal_500_primary</item>

<!-- darker variant for the status bar and contextual app bars -->
<item name="colorPrimaryDark">@color/md_teal_700</item>

<!-- theme UI controls like checkboxes and text fields -->
<item name="colorAccent">@color/md_teal_900</item>


</style>

</resources>



Screenshot:
======





















Update:
======

Since the spinner dropdown is not like the new LollyPop Design like Spinner:

We need to add small code for the spinner control

 android:dropDownVerticalOffset="-52dp" for Kitkat and below

 android:dropDownVerticalOffset="0dp" for LollyPop



 <Spinner
        android:id="@+id/spinner_nav"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:dropDownVerticalOffset="@dimen/dropDownVerticalOffset" />


Tuesday, December 30, 2014

RecyclerView with onClick and onLongClick implemtation in android example

In the Previous Post, We have create list of items with RecyclerView using appcompat v7.

Now, we have implemented onclick event functionality in the previous post for each list item using stackoverflow link.

Now, I have update the code to latest Android Api RecyclerView default way of implementing
onClick and onLongClick on the each item.


Step 1: Create an Activity with recyclerview

CardViewActivity.java
package com.pratap.cardviews1;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;

public class CardViewActivity extends AppCompatActivity {

private Toolbar toolbar;

private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

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

if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Versions");

}

final String[] myDataset = { "Alpha", "Beta", "CupCake", "Donut",
"Eclair", "Froyo", "Gingerbread", "Honeycomb",
"Ice Cream Sandwitch", "JellyBean", "KitKat", "LollyPop" };

mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);

// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));


// create an Object for Adapter
mAdapter = new CardViewDataAdapter(myDataset);

// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);

}

}

Step 2:  Create an Adapter for the recycler with the class RecyclerView.Adapter


CardViewDataAdapter.java

package com.pratap.cardviews1;


import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class CardViewDataAdapter extends
RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private static String[] mDataset;



// Provide a suitable constructor (depends on the kind of dataset)
public CardViewDataAdapter(String[] myDataset) {
mDataset = myDataset;

}

// Create new views (invoked by the layout manager)
@Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.cardview_row, null);

// create ViewHolder

ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData

viewHolder.tvVersionName.setText(mDataset[position].toString());

viewHolder.versionName=mDataset[position];

}

// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}

// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {

public TextView tvVersionName;

public String versionName;

public ViewHolder(View itemLayoutView) {
super(itemLayoutView);

tvVersionName = (TextView) itemLayoutView
.findViewById(R.id.tvVersionName);

itemLayoutView.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

Toast.makeText(v.getContext(), "OnClick Version :" + versionName,
Toast.LENGTH_SHORT).show();

}
});

itemLayoutView.setOnLongClickListener(new OnLongClickListener() {

@Override
public boolean onLongClick(View v) {

Toast.makeText(v.getContext(), "OnLongClick Version :" + versionName,
Toast.LENGTH_SHORT).show();
return true;

}
});

}

}

}


Step 3:

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar 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/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >

</android.support.v7.widget.Toolbar>

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"
android:background="#c9c9c9"
android:orientation="vertical" >

<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />

<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:scrollbars="vertical" />

</LinearLayout>

Step 4:

cardview_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" >

<TextView
android:id="@+id/tvVersionName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:minHeight="55dp"
android:textColor="@android:color/black"
android:textSize="24sp" />
</RelativeLayout>

</android.support.v7.widget.CardView>


Step 5:

values/themes.xml

<resources>

<style name="AppTheme" parent="AppTheme.Base" />

<style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<!-- <item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item> -->

</style>

</resources>

Step 6:

values-21/themes.xml

<resources>
<style name="AppTheme" parent="AppTheme.Base">
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
<item name="android:windowSharedElementExitTransition">@android:transition/move</item>
</style>
</resources>

Step 7:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pratap.cardviews1"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".CardViewActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Step 8:

Run the Application:

Download the Source Code

ScreenShots



recyclerview onclick
recyclerview onlongclick

Thursday, December 18, 2014

Using Toolbar in android in LollyPop and Pre-Lollypop Devices - Part 2



1) toolbar.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar 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/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/md_blue_500_primary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>


2) activity_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:orientation="vertical" >

<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Name"
android:inputType="textPersonName"
android:textColor="@color/md_black">
<requestFocus />
</EditText>

</LinearLayout>


3)  MainActivity.java


package com.pratap.materialdesign;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;

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

toolbar = (Toolbar) findViewById(R.id.toolbar);

toolbar.setTitle("Material Design");
//toolbar.setSubtitle("AppCompat");
//toolbar.setTitleTextColor(Color.RED);

setSupportActionBar(toolbar);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}




4) values/styles.xml

<resources>
    <!-- Base application theme using AppCompatv21 Library -->
<style name="AppBaseTheme" parent="Theme.AppCompat">

<!-- your app branding color for the app bar -->
<item name="colorPrimary">@color/md_blue_500_primary</item>

<!-- darker variant for the status bar and contextual app bars -->
<item name="colorPrimaryDark">@color/md_blue_700</item>

<!-- Change the Background color of the window in the activity -->
<item name="android:windowBackground">@color/md_white</item>
<!-- theme UI controls like checkboxes and text fields -->
<item name="colorAccent">@color/md_red_200</item>

<!-- Chnaging the toolbar text color -->
<!-- <item name="android:textColorPrimary">@color/md_red_500_primary</item> -->

<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme"></style>

</resources>

5) values-21/styles.xml

<resources>

<style name="AppTheme" parent="AppBaseTheme">
<!-- API 21 theme customizations can go here. -->

<item name="android:navigationBarColor">@color/md_cyan_500_primary</item>
</style>

</resources>


6)  AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pratap.materialdesign"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



7) Build and Run the Code


ScreenShot: