Friday, 11 September 2015

create a list

To create a list

We extend mainActivity as ListActivity

set ListAdapeter as

setListAdapter(new MyAdapter(this,android.R.layout.simple_list_item_1,R.id.textView,getResources().getStringArray(R.array.countries)));
 
Myadapter class is a custom class created by us so will need to be redefined later to create the options list as we want
 or in simple case it wud have been ArrayAdapter which is already defined
 
 
 
 Then we have out oncreateOptionsMenu
 
@Overridepublic boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
 
in the above code inflater class holds to change the options as we want
here its refering to a xml file helping it modify the options as the xml file looks 
 
 
Now the options in the list being selected we havee a different claass to handle that
 
@Overridepublic 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();

    //noinspection SimplifiableIfStatement    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
} 
 
 
 Our Myadapter class
 
private  class MyAdapter extends ArrayAdapter<String>{

        public MyAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
            super(context, resource, textViewResourceId, objects);
        }

        @Override        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater layoutinflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE );
            View row= layoutinflater.inflate(R.layout.llist_item,parent, false);
            String[] items= getResources().getStringArray(R.array.countries);
            ImageView im= (ImageView) row.findViewById(R.id.imageView);
            TextView tv= (TextView) row.findViewById(R.id.textView);
            tv.setText(items[position]);
            if(items[position].equals("United states"))
            {
                im.setImageResource(R.drawable.usa);
            }
            if(items[position].equals("United kingdom"))
            {
                im.setImageResource(R.drawable.france);
            }


            return row;
        }
    }
} 
 
 
overrides the getview of arrayAdapter to customize the view 

No comments:

Post a Comment