Showing posts with label Spinner. Show all posts
Showing posts with label Spinner. Show all posts

Wednesday, 10 June 2015

Create Form Programmatically in Android



Step: 1

create a new xml layout with scrollview and LinearLayout . We create child view dynamically through code , added to the LinearLayout.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="false"
    android:scrollbars="none"
    android:layout_margin="16dp">

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        ></LinearLayout>

</ScrollView>

Step: 2

create new Activity class


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package com.pratap.dynamicforms;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.List;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * Created by pratap.kesaboyina on 10-06-2015.
 */
public class DynamicForm extends AppCompatActivity {


    LinearLayout layout1;
    private static int viewsCount = 0;
    private List<View> allViews = new ArrayList<View>();
    LinearLayout.LayoutParams params;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dynamic_form);

        // To set Margin for the child Views
       params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(5, 5, 5, 5);

        // LinearLayout acts as parent Layout , we will add child Views to this Layout dynamically
        layout1 = (LinearLayout) findViewById(R.id.layout1);
        // Sample Data for Spinner
        ArrayList<String> spinnerList = new ArrayList<String>();
        spinnerList.add("Select");
        spinnerList.add("Hyderabad");
        spinnerList.add("Banglore");
        spinnerList.add("Chennai");
        spinnerList.add("Delhi");
        spinnerList.add("Mumbai");

// create edittext dynamically , added to LinearLayout
        createEditText("First Name");
        createEditText("Last Name");
        createEditText("Age");
        createEditText("Address");
        createSpinner(spinnerList);
        createEditText("State");


// create spinners dynamically , added to LinearLayout


// create checkbox dynamically , added to LinearLayout
        createCheckBox("Key Contact");
        createCheckBox("Target contact");
        saveButton();

    }

// create a button to show/save data , entered in the Form
    private void saveButton() {
        Button saveButton = new Button(this);
        saveButton.setHeight(WRAP_CONTENT);
        saveButton.setText("Save");
        saveButton.setOnClickListener(submitListener);
        layout1.addView(saveButton,params);
    }

    // Access the value of the EditText

    private View.OnClickListener submitListener = new View.OnClickListener() {
        public void onClick(View view) {
            StringBuilder stringBuilder = new StringBuilder();
            for (View singView : allViews) {

                String className = Utils.getClassName(singView.getClass());

                if (className.equalsIgnoreCase("EditText")) {
                    EditText editText = (EditText) singView;
                    stringBuilder.append(" "+editText.getText().toString());
                } else if (className.equalsIgnoreCase("Spinner")) {
                    Spinner spiner = (Spinner) singView;
                    stringBuilder.append(" "+spiner.getSelectedItem());
                }
                else if (className.equalsIgnoreCase("CheckBox")) {
                    CheckBox checkBox = (CheckBox) singView;
                    stringBuilder.append(" "+checkBox.isChecked());
                }

            }
            Log.i("All Data ", stringBuilder.toString());

            Utils.showAlertDialog(view.getContext(), "Data", stringBuilder.toString());
        }
    };


    public void createEditText(String hint) {
        EditText editText = new EditText(this);
        editText.setId(viewsCount++);
        editText.setHint(hint);
        allViews.add(editText);
        layout1.addView(editText,params);

    }

    public void createSpinner(List<String> spinnerList) {



        Spinner spinner = new Spinner(this);
        spinner.setId(viewsCount++);
        spinner.setBackgroundResource(R.drawable.dropdown_normal_holo_light);
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerList);
        spinner.setAdapter(spinnerArrayAdapter);
        allViews.add(spinner);
        layout1.addView(spinner,params);
    }


    public void createCheckBox(String label) {

        final CheckBox checkBox = new CheckBox(this);
        checkBox.setId(viewsCount++);
        checkBox.setText(label);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });
        allViews.add(checkBox);
        layout1.addView(checkBox,params);
    }




}

Util.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.pratap.dynamicforms;

import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class Utils

{


    public static void showAlertDialog(Context context, String title,
                                       String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        if (title != null)
            builder.setTitle(title);
        builder.setMessage(message);
        builder.setNegativeButton("OK", null);
        builder.show();
    }

    /**
     *
     * @param c
     * @return
     */

    public static String getClassName(Class c) {
        String className = c.getName();
        int firstChar;
        firstChar = className.lastIndexOf('.') + 1;
        if (firstChar > 0) {
            className = className.substring(firstChar);
        }
        return className;
    }
}

Screen Shot






















Download Source Code Link

Friday, 30 January 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" />