Show ListView as Dropdown in Android – a Spinner Alternative

Our code for today will give us an alternative to using the Android spinner. We will show ListView as dropdown in Android. This ListView dropdown works just like a spinner but:

  • I love how it looks and response to user touch, it feels smoother and faster than a spinner.
  • It can also be easily customized, you won’t have to get stuck with default spinner look.
  • It can be triggered on any view elements such as a Button, Layout, TextView or EditText.

MainActivity.java – shows the button, set the items for the drop down list, creates the pop up window and then show it as drop down when the button was touched.

import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;
public class MainActivity extends Activity {
    String TAG = "MainActivity.java";
    String popUpContents[];
    PopupWindow popupWindowDogs;
    Button buttonShowDropDown;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initialize pop up window items list
        
        // add items on the array dynamically
        // format is DogName::DogID
        List<String> dogsList = new ArrayList<String>();
        dogsList.add("Akita Inu::1");
        dogsList.add("Alaskan Klee Kai::2");
        dogsList.add("Papillon::3");
        dogsList.add("Tibetan Spaniel::4");
        // convert to simple array
        popUpContents = new String[dogsList.size()];
        dogsList.toArray(popUpContents);
        
        // initialize pop up window
        popupWindowDogs = popupWindowDogs();
        
        // button on click listener
        
        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {                                                                                                                                                                                                                                                                                                
                switch (v.getId()) {
                case R.id.buttonShowDropDown:
                    // show the list view as dropdown
                    popupWindowDogs.showAsDropDown(v, -5, 0);
                    break;
                }
            }
        };
        // our button
        buttonShowDropDown = (Button) findViewById(R.id.buttonShowDropDown);
        buttonShowDropDown.setOnClickListener(handler);
    }
    public PopupWindow popupWindowDogs() {
        // initialize a pop up window type
        PopupWindow popupWindow = new PopupWindow(this);
        // the drop down list is a list view
        ListView listViewDogs = new ListView(this);
        
        // set our adapter and pass our pop up window contents
        listViewDogs.setAdapter(dogsAdapter(popUpContents));
        
        // set the item click listener
        listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());
        // some other visual settings
        popupWindow.setFocusable(true);
        popupWindow.setWidth(250);
        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        
        // set the list view as pop up window content
        popupWindow.setContentView(listViewDogs);
        return popupWindow;
    }
    /*
     * adapter where the list values will be set
     */
    private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // setting the ID and text for every items in the list
                String item = getItem(position);
                String[] itemArr = item.split("::");
                String text = itemArr[0];
                String id = itemArr[1];
                // visual settings for the list item
                TextView listItem = new TextView(MainActivity.this);
                listItem.setText(text);
                listItem.setTag(id);
                listItem.setTextSize(22);
                listItem.setPadding(10, 10, 10, 10);
                listItem.setTextColor(Color.WHITE);
                
                return listItem;
            }
        };
        
        return adapter;
    }
}
DogsDropdownOnItemClickListener.java – triggered when an item on the drop down list was touched, it will change the text on the button and show a toast with the ID of the selected item.
import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class DogsDropdownOnItemClickListener implements OnItemClickListener {
    String TAG = "DogsDropdownOnItemClickListener.java";
    
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
        // get the context and main activity to access variables
        Context mContext = v.getContext();
        MainActivity mainActivity = ((MainActivity) mContext);
        
        // add some animation when a list item was clicked
        Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
        fadeInAnimation.setDuration(10);
        v.startAnimation(fadeInAnimation);
        
        // dismiss the pop up
        mainActivity.popupWindowDogs.dismiss();
        
        // get the text and set it as the button text
        String selectedItemText = ((TextView) v).getText().toString();
        mainActivity.buttonShowDropDown.setText(selectedItemText);
        
        // get the id
        String selectedItemTag = ((TextView) v).getTag().toString();
        Toast.makeText(mContext, "Dog ID is: " + selectedItemTag, Toast.LENGTH_SHORT).show();
        
    }
}
activity_main.xml – Here is the XML layout file we used for the user interface of our example.
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
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=”.MainActivity” >

<Button
android:id=”@+id/buttonShowDropDown”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:text=”Select your dog…” />

</RelativeLayout>

Advertisements

Difference between px, dp, dip and sp in Android

  • px is one pixel.
  • sp is scale-independent pixels.
  • dip is Density-independent pixels. enter image description here

You would use

  • sp for font sizes
  • dip for everything else.

    dip==dp

px
Pixels – corresponds to actual pixels on the screen.

in
Inches – based on the physical size of the screen.
1 Inch = 2.54 centimeters

mm
Millimeters – based on the physical size of the screen.

pt (it depends upon physical size of the screen) Points – 1/72 of an inch based on the physical size of the screen.

This will help you for more understanding.

enter image description here

dp
Density-independent Pixels – an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.

sp
Scale-independent Pixels – this is like the dp unit, but it is also scaled by the user’s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user’s preference.

 

Working on multiple SVN branches in 1 Eclipse Workspace

We have a tree in svn. Need to checkout trunk, one version of branches and another version of branches in Eclipse. How to achieve this?

Example Structure

\repo
  \Project1
    \branches
    \tags
    \trunk
  \Project2
    \branches
    \tags
    \trunk
  \Project3
    \branches
    \tags
    \trunk

Step 1:

Go to repository location

Step 2 :

Right Click on branch or trunk whatever –> Find/Check Out As…

Step 3:

Set the unique name for project. Click OK

Note: This name must not be the existing project name.

Removing a workspace from Eclipse workspace launcher history

If you have recently deleted a workspace from Eclipse and purged all the files from your file system, you may find it annoying that Eclipse will still show the workspace in the workspace launcher dialog.  If you are trying to explain what workspace another developer needs to access, it can also lead to unnecessary confusion.

Ecplise stores the workspace history in a preferences file calledorg.eclipse.ui.ide.prefs located under %ECLIPSE_HOME%\configuration\.settings. The RECENT_WORKSPACES key contains a comma separated list of workspace paths. You can remove either the entire line (key & values) or just one value from the list.Shutdown Eclipse, update the org.eclipse.ui.ide.prefs file and restart Eclipse and the workspace should no longer appear in the launcher.

Get the launcher activity of all packages in Android Device

final PackageManager pm = getPackageManager();

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

List<ResolveInfo> appList = pm.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm));

for (ResolveInfo temp : appList) {

Log.e(“my logs”, “package and activity name = ”
+ temp.activityInfo.packageName + ” ”
+ temp.activityInfo.name);

}

How to Create a Undeletable and Unrenamable Folders in Windows

How to Create a Undeletable and Unrenamable Folders in Windows

  • Go to Start and then Click on Run
  • Type cmd and hit enter
  • Remember you cannot create Undeletable & unrenamable folder in your root directory (i.e. where the windows is installed) That means you can’t make this kind of folder in C: drive if you installed windows on C:
  • Type D: or E: and hit enter
  • Type md con\ and hit enter (md – make directory)
  • You may use other words such as aux, lpt1, lpt2, lpt3 up to lpt9 instead of con in above step.
  • Open that directory, you will see the folder created of name con.
  • Try to delete that folder or rename that folder windows will show the error message.

How to Delete those files

You can’t delete the file in normal way. So follow these steps
  • Open Command Prompt
  • Type D: ( if u created this type of folder in D: drive) & hit enter
  • Type rd con\ (rd – remove directory)
  • Open that directory and the folder will not appear because it is removed.