Add icons to menu list options - android

Many answers on SO would seem to suggest that it is not possible to add icons to the overflow menu list, however a number of apps, eg Contacts, (see image) have not only done just that but also have a rather nice border with rounded corners and make it appear by sliding up. How can I do the same? The standard menuinflater only adds icons to the action bar

You need to create a layout for represents each option and put that with a adapater.
I do something like this:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayoutItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center"
android:paddingBottom="5sp"
android:paddingLeft="5sp"
android:paddingTop="5sp" >
<ImageView
android:id="#+id/dliIVImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dip"
android:maxHeight="20sp"
android:maxWidth="20sp"
android:src="#drawable/icon" />
<TextView
android:id="#+id/dliLblOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/activatedBackgroundIndicator"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#fff" />
</LinearLayout>
Adapter:
public class MenuAdapter extends BaseAdapter {
private String[] options;
private LayoutInflater mInflater;
private ViewHolder holder;
public static final Integer[] images = { R.drawable.icon_search,
R.drawable.icon_profile, R.drawable.icon_password, R.drawable.icon_locate, R.drawable.icon_logout};
static class ViewHolder{
private TextView option;
private ImageView img;
}
public MenuAdapter(Context context, String[] options) {
mInflater = LayoutInflater.from(context);
this.options = options;
}
#Override
public int getCount() {
return options.length;
}
#Override
public Object getItem(int index) {
return options[index];
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(int posicao, View convertView, ViewGroup arg2) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
holder = new ViewHolder();
holder.option = (TextView) convertView.findViewById(R.id.dliLblOption);
holder.img = (ImageView) convertView.findViewById(R.id.dliIVImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.option.setText(options[posicao]);
holder.img.setImageResource(images[posicao]);
return convertView;
}
}
Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
opcoes = ["option1", "option2", "option3"];
MenuAdapter mAdapter = new MenuAdapter(getApplicationContext(), opcoes);
menuLateral = (DrawerLayout) findViewById(R.id.drawer_layout);
listaMenuLateral = (ListView) findViewById(R.id.left_drawer);
listaMenuLateral.setAdapter(mAdapter);
}
Main Layout
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>

Related

Changing the background of list items by click on a separate button

I have a listView with some items now I want to change the background color or item text color by click on a separate button which IS NOT on the list . How can I do that in my android app?
This is my main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayAdapter = new SubArrayAdapter(this, dataItemList);
ListView lv = findViewById(R.id.mylist);
lv.setAdapter(arrayAdapter);
ImageButton btn_check = findViewById(R.id.button_checkout);
btn_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// how can I access the list items within this click-handler method
});
List Item Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listitems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<ImageView
android:id="#+id/yes_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:paddingRight="5dp"
android:visibility="invisible"
/>
<ImageView
android:id="#+id/no_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:paddingRight="5dp"
android:visibility="invisible"
/>
<TextView
android:id="#+id/paragraph_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/yes_image"
android:layout_toRightOf="#id/yes_image"
android:textColor="#color/paragraph_items_colro"
android:textSize="16sp"
android:textStyle="normal" />
</RelativeLayout>
Activity_main xml layout file:
android.support.constraint.ConstraintLayout
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/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:textDirection="ltr"
tools:context=".MainActivity">
<ListView
android:id="#+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#android:color/transparent"
android:divider="#color/colorAccent"
android:dividerHeight="1dp"
android:listSelector="#0f0"
app:layout_constraintStart_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</ListView>
<LinearLayout
android:id="#+id/btn_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#id/mylist">
<ImageButton
android:id="#+id/button_checkout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/checkout_9"
android:src="#drawable/checkout_9"
app:layout_constraintTop_toBottomOf="#id/mylist"
tools:layout_editor_absoluteX="106dp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
And I have myown adapter class that in the getview() method I populated the list items
this inner class is located in mainactivity:
private class SubArrayAdapter extends ArrayAdapter<DataItem> {
private List<DataItem> items;
private Context context;
public SubArrayAdapter(#NonNull Context context, #NonNull List<DataItem>
items) {
super(context, R.layout.listitems, items);
this.items = items;
this.context = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
DataItem dataitem1 = items.get(position);
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.listitems, null);
TextView tv = (TextView)
view.findViewById(R.id.paragraph_description);
tv.setText(dataitem1.getDescription());
tv.setTag(position + 100);
ImageView yes_iv = view.findViewById(R.id.yes_image);
int yes_res = context.getResources().getIdentifier("yes",
"drawable", getPackageName());
yes_iv.setImageResource(yes_res);
yes_iv.setTag(position + 200);
//yes_iv.setVisibility(View.VISIBLE);
ImageView no_iv = view.findViewById(R.id.no_image);
int no_res = context.getResources().getIdentifier("no", "drawable",
getPackageName());
no_iv.setImageResource(no_res);
no_iv.setTag(position + 300);
return view;
}
}
}
I've noticed You have set android:listSelector for ListView in Your activity_main.xml - which was giving You an ability to change item's background on single click.
So I decided to check out how it works in ListView class.
I've looked at source code of ListView and searched for phrase selector. There was the line:
} else if (mAction == STATE_REQUEST_FOCUS) {
final int childIndex = mPosition - mFirstPosition;
final View child = getChildAt(childIndex);
if (child != null) {
child.requestFocus();
}
mAction = -1;
}
final View child = getChildAt(childIndex);
Following these steps - I knew solution for Your question problem. Here it is:
ImageButton imageButton = findViewById(R.id.button_checkout);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int hardCodedPoositionToSelect = 1;
View childAt = listView.getChildAt(hardCodedPoositionToSelect);
if (childAt != null) {
//change background
childAt.setBackgroundColor(Color.RED);
//change textView color of current view
TextView paragraphDescription = childAt.findViewById(R.id.paragraph_description);
paragraphDescription.setTextColor(Color.MAGENTA);
}
}
});
You can see I am calling getChildAt() on listView to obtain current item's view basing on item's position from hardCodedPoositionToSelect.

Different background color for each drawer menu item

I'm developing a native android app with xamarin. I need to set a different background color for each item of drawer menu and it should be extended for the whole width of drawer.
In this moment, the menu items styles, are set in the drawer activity, in this way:
itemOrdini = navigationView.Menu.FindItem(Resource.Id.nav_ordini);
Android.Text.SpannableString spanString = new Android.Text.SpannableString(itemOrdini.ToString());
spanString.SetSpan(new Android.Text.Style.ForegroundColorSpan(Resources.GetColor(Resource.Color.rosso_ordini)), 0, spanString.Length(), 0);
itemOrdini.SetTitle(spanString);
notificheOrdini.Gravity = GravityFlags.CenterVertical;
notificheOrdini.Typeface = Typeface.DefaultBold;
notificheOrdini.SetTextColor(Resources.GetColor(Resource.Color.rosso_ordini));
is there a way to achieve the result?
You could try to use a custom listview to instead of the NavigationView.
The text color and background color could be set in the adapter's GetView method.
You could refer to following links for more information:
Create a Custom Adapter for Contacts
For example:
Main.axml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:id="#+id/drawer_layout">
<!-- your content layout -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
MenuList.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/ItemIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="5dp" />
<TextView
android:id="#+id/ItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp" />
</LinearLayout>
MainActivity.cs
public class MainActivity : AppCompatActivity
{
DrawerLayout drawerLayout;
ListView DrawerList;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
drawerLayout = (DrawerLayout)FindViewById(Resource.Id.drawer_layout);
DrawerList = (ListView)FindViewById(Resource.Id.left_drawer);
DrawerList.Adapter =new MenuListAdapter(this);
DrawerList.OnItemClickListener = new onClickListener();
}
}
public class onClickListener :Java.Lang.Object, IOnItemClickListener
{
public void OnItemClick(AdapterView parent, View view, int position, long id)
{
}
}
And the adapter
public class MenuListAdapter : BaseAdapter
{
List<MenuItems> Items;
public override int Count => Items.Count;
Activity _activity;
public MenuListAdapter(Activity activity)
{
_activity = activity;
Items = new List<MenuItems>();
Items.Add(new MenuItems() { color = Color.Azure, ItemName = "Home" });
Items.Add(new MenuItems() { color = Color.Green, ItemName = "Home" });
Items.Add(new MenuItems() { color = Color.DarkGoldenrod, ItemName = "Home" });
}
public override Java.Lang.Object GetItem(int position)
{
return Items[position];
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var view = convertView ?? _activity.LayoutInflater.Inflate(
Resource.Layout.MenuList, parent, false);
var Name = view.FindViewById<TextView>(Resource.Id.ItemName);
var Icon = view.FindViewById<ImageView>(Resource.Id.ItemIcon);
Name.Text = Items[position].ItemName;
view.SetBackgroundColor(Items[position].color);
return view;
}
}
class MenuItems : Java.Lang.Object
{
public string ItemName { get; set; }
public Color color { get; set; }
}

Android ListView requires two fingers to scroll

I have a rather simple layout that I am intending on using for basic chat in a fragment, but scrolling through the ListView requires me to place one finger on the screen on an item in the ListView and then scroll up or down with another finger. I was under the impression that a ListView should only require a single finger/touch to be able to scroll. Is there something I am overlooking in my layout, adapter or even potentially the code I am using to populate the adapter with?
Chat Layout XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
<ListView
android:id="#+id/msgListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/form"
android:divider="#null"
android:dividerHeight="0dp"
android:scrollbarSize="3dp"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:paddingBottom="10dp" />
<LinearLayout
android:id="#+id/form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#color/primary"
android:orientation="horizontal"
android:paddingBottom="2dp" >
<EditText
android:id="#+id/messageEditText"
android:layout_width="252dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/button1"
android:layout_toLeftOf="#+id/sendMessageButton"
android:layout_weight="0.72"
android:ems="10"
android:maxHeight="80dp" />
<ImageButton
android:id="#+id/sendMessageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/chat_send_button" />
</LinearLayout>
</RelativeLayout>
ListView Adapter
public class ChatMessageAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
ArrayList<ChatMessage> chatMessageList;
public ChatMessageAdapter(Activity activity, ArrayList<ChatMessage> list) {
chatMessageList = list;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return chatMessageList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage message = chatMessageList.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chat_bubble, null);
TextView msg = (TextView) vi.findViewById(R.id.message_text);
msg.setText(message.body);
TextView dateTime = (TextView) vi.findViewById(R.id.msgDateTime);
dateTime.setText(message.dateTime);
LinearLayout layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout);
LinearLayout parent_layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout_parent);
// if message is mine then align to right
if (message.isMine) {
layout.setBackgroundResource(R.drawable.bubble2);
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
layout.setBackgroundResource(R.drawable.bubble1);
parent_layout.setGravity(Gravity.LEFT);
}
msg.setTextColor(Color.BLACK);
return vi;
}
public void add(ChatMessage object) {
chatMessageList.add(object);
}
}
I had the same problem!
If you're using the navigation drawer, in the app_bar_main.xml change the CoordinatorLayout for the NestedScrollView
and then in your fragment in the scrollView set android:nestedScrollingEnabled="true"

Navigation drawer menu item with titles and sub titles

I have a navigation drawer prototype. we have heading and subheading in the same. am using menu group to include the titles.
1) just want to add sub title or help text for the navigation drawer.
2) want to customise the icon size to fit the whole heading and sub heading so it looks like the image below.
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_home"
android:subtitle="View your biorhythm" <!-- This should be sub title. -->
android:title="Home"
/>
Inside in DrawerLayout create ListView using below code
<!-- List of Actions (pages) -->
<ListView
android:id="#+id/navList"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_below="#+id/profileBox"
android:choiceMode="singleChoice"
android:background="#ffffffff" />
Now Create one Class that contain property for Title, SubTitle and Icon like below.
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, String subtitle, int icon) {
mTitle = title;
mSubtitle = subtitle;
mIcon = icon;
}
}
Now Create Adapter for that
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
subtitleView.setText( mNavItems.get(position).mSubtitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
Create Listview item xml to get your format
<?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="match_parent"
android:paddingTop="10dp"
android:paddingBottom="10dp">
<ImageView
android:id="#+id/icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/ic_action_home"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginRight="20dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center_vertical"
android:textColor="#000"
android:text="Line 1"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/icon"
android:layout_toEndOf="#+id/icon" />
<TextView android:id="#+id/subTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Line 2"
android:layout_toRightOf="#+id/icon"
android:layout_below="#+id/title"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
and Finally Add into MainActivity.java file like below way.
private static String TAG = MainActivity.class.getSimpleName();
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavItems.add(new NavItem("Home", "Meetup destination", R.drawable.ic_action_home));
mNavItems.add(new NavItem("Preferences", "Change your preferences", R.drawable.ic_action_settings));
mNavItems.add(new NavItem("About", "Get to know about us", R.drawable.ic_action_about));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
You will get Below Output :

Android custom ListView layout problems

Hi guys, I tried to learn how to use custom ListView by this page
It works fine but I have problems with another options.
Cannot set margin to listItems
Cannot set backgro
Cannot set OnItemClickListener
1# Margin
First of all I'm trying to set margin between list items but nothing works. I try to set margin on RelativeLayout in rowlayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
2# Background
I want to set background on whole screen under listView. I think I put black color on every View in every xml I found but nothing affect the background. I can change background of single list items, that's all.
android:background="#000000"
3#OnItemClickListener
My last problem is that I'm not able to set onItemClickListener. I have no idea how to set it if I don't have simply ListView but RelativeLayout with TextView etc.
I guess I have to use
setOnClickListener(new OnClickListener()
and after that
public void onClick(View arg0) {
but I have no idea on which View I have to use this method.
Files
MyAdapter.java
public class MyAdapter extends ArrayAdapter<Model> {
private final Context context;
private final ArrayList<Model> modelsArrayList;
public MyAdapter(Context context, ArrayList<Model> modelsArrayList) {
super(context, R.layout.rowlayout, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = null;
if(!modelsArrayList.get(position).isGroupHeader()){
rowView = inflater.inflate(R.layout.rowlayout, parent, false);
// 3. Get icon,title & counter views from the rowView
ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
TextView counterView = (TextView) rowView.findViewById(R.id.item_counter);
// 4. Set the text for textView
imgView.setImageResource(modelsArrayList.get(position).getIcon());
titleView.setText(modelsArrayList.get(position).getTitle());
counterView.setText(modelsArrayList.get(position).getCounter());
}
else{
//rowView = inflater.inflate(R.layout.group_header, parent, false);
// TextView titleView = (TextView) rowView.findViewById(R.id.header);
// titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Model.java
package com.example.sunny.katan;
/**
* Created by Sunny on 15.09.14.
*/
public class Model{
private int icon;
private String title;
private String counter;
private boolean isGroupHeader = false;
public Model(String title) {
this(-1,title,null);
isGroupHeader = true;
}
public Model(int icon, String title, String counter) {
super();
this.icon = icon;
this.title = title;
this.counter = counter;
}
public String getCounter() {
return counter;
}
public String getTitle() {
return title;
}
public int getIcon() {
return icon;
}
public boolean isGroupHeader() {
return false;
}
public void setGroupHeader(boolean isGroupHeader) {
this.isGroupHeader = isGroupHeader;
}
//gettters & setters...
}
main.java
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// if extending Activity
//setContentView(R.layout.activity_main);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
// if extending Activity 2. Get ListView from activity_main.xml
//ListView listView = (ListView) findViewById(R.id.listview);
// 3. setListAdapter
//listView.setAdapter(adapter); if extending Activity
setListAdapter(adapter);
}
private ArrayList<Model> generateData(){
ArrayList<Model> models = new ArrayList<Model>();
models.add(new Model(R.raw.barbell,"Cviky","37"));
models.add(new Model(R.raw.stretching,"Protahování","94"));
models.add(new Model(R.raw.work,"Generování workoutu","293"));
return models;
}
rowlayout.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="75dp"
android:background="#drawable/rounded"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
<!-- icon -->
<ImageView
android:id="#+id/item_icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:src="#raw/barbell"
/>
<!-- title -->
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/item_icon"
android:layout_marginTop="30dp"
android:layout_alignBaseline="#+id/item_counter"
android:textSize="20dp"
/>
<!-- counter -->
<TextView
android:id="#+id/item_counter"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:layout_centerVertical="true"
android:background="#drawable/rectangle"
android:gravity="center"
android:textColor="#FFFFFF"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="false"
>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".katan_lobby"
android:orientation="vertical"
>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/menu"
android:layout_gravity="center_horizontal"
android:background="#238CD4"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/prvniItemSeznamu"
android:background="#238CD4"
style="#style/listView"
/>
</LinearLayout>
</ScrollView>
Looks like you are half way there in your activity.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
MyAdapter adapter = new MyAdapter(this, generateData());
ListView listView = (ListView) findViewById(R.id.menu);
listView.setAdapter(adapter); if extending Activity
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//You now have the position but you will need to get your model list and use .get(position) and cast it to Model to get access to it.
}
});
}
//First define your list view item xml… something like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/white"
android:layout_marginTop="10dp"
android:padding="10dp" >
<TextView
android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/custom_blue"
android:text="TextView" />
<TextView
android:id="#+id/item2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="#color/custom_grey"
android:text="TextView" />
</LinearLayout>
//Then you define your list list adapter.
public class MyListAdapter extends ArrayAdapter<MyModel> {
private Context context;
private ArrayList<MyModel> myModel;
public MyListAdapter(Context context, ArrayList<MyModel> myModelList) {
super(context, R.id.icon, myModelList);
this.context = context;
this.myModelList = myModelList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = null;
View rowView = convertView;
TextView myItemName = (TextView)rowView.findViewById(R.id.item1);
TextView myItemTitle = (TextView)rowView.findViewById(R.id.item2);
//use your models getters/setters
myItemName.setText(myModelList.get(position).getItemTitle());
myItemTitle.setText(myModelList.get(position).getItemName());
return rowView
}
}
//Now use both the list adapter and list item in your ListFragment or ListActivity.
ArrayList<MyModel> myModelList = new ArrayList<MyModel>();
MyListAdapter myApt = new MyListAdapter(this, myModelList);
setListAdapter(myApt);
//For clicking on the items:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// ListView Clicked item value
String itemValue = l.getItemAtPosition(position).toString();
doSomethingWihtMyItemMethod(position);
}
/* You can customize your list item anyway you like, just be aware of screen real estate when doing so.Hope this helps. */

Categories

Resources