I am new to android and my an using list view, I want to change list item color on selection but it is not working.
I have check almost all links on stack overflow and tried them all but no luck... Please check my code ... and tell me where is the problem.
public class Main extends Activity {
private ListView listView;
private String[] menuArray;
private List<String> menuList = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
menuArray = getResources().getStringArray(R.array.Menu);
menuList = Arrays.asList(menuArray);
listView = (ListView) findViewById(R.id.listView_main_menu);
listView.setAdapter(new EfficientAdapter(this,menuList));
}
/******************************** EfficientAdapter ************************************/
public class EfficientAdapter extends BaseAdapter{
private LayoutInflater mInflater;
#SuppressWarnings("unused")
private String TAG=EfficientAdapter.class.getSimpleName();
#SuppressWarnings("unused")
private Context context;
private List<String> data= new ArrayList<String>();
public EfficientAdapter(Context context,List<String> data) {
super();
mInflater = LayoutInflater.from(context);
this.context=context;
this.data.addAll(data);
}
public EfficientAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
this.context=context;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(R.layout.main_list, null);
holder = new ViewHolder();
holder.textLine = (TextView) convertView.findViewById(R.id.textView_mainlist_item);
convertView.setTag(holder);
}
holder =(ViewHolder) convertView.getTag();
holder.textLine.setText(getItem(position));
convertView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return convertView;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public String getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView textLine;
}
}
}
Here is my xml file with list view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/Gainsboro"
android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:id="#+id/listView_main_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
android:choiceMode="singleChoice"
android:divider="#color/DarkGray"
android:dividerHeight="1dip"
android:fadingEdge="none"
android:listSelector="#drawable/row_color"
android:scrollbars="none" >
</ListView>
</RelativeLayout>
row_color.xml
<item android:state_pressed="false" android:state_focused="false"
android:drawable="#color/Green" />
<item android:state_focused="true"
android:drawable="#color/Blue" />
<item android:state_pressed="true"
android:drawable="#color/Brown" />
<item
android:state_selected="true" android:drawable="#color/Cyan" />
main_list.xml; this xml contain textview which is inflating
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView_mainlist_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:text="TextView"
android:textColor="#color/DarkSlateGray"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right|center"
android:paddingRight="30dp"
android:paddingTop="6dp"
android:text=">"
android:textColor="#color/DarkSlateGray"
android:textSize="28sp"
android:textStyle="bold" />
</FrameLayout>
Just found that only this portion is working fine
<item android:state_pressed="false" android:state_focused="false"
android:drawable="#color/Green" />
Instead of
convertView = mInflater.inflate(R.layout.main_list, null);
Try
convertView = mInflater.inflate(R.layout.main_list, parent, false);
EDIT:
I see what you are trying to do now. You don't want to have android:ListSelector on ListView, but rather on each individual FrameLayout. So:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:listSelector="#drawable/row_color" >
You would need to apply it to each individual view in order to have them change color when pressed, etc.
Visit http://android-codes-examples.blogspot.in/2011/03/customized-listview-items-selection.html
Hope it works for you
Related
I am new to android and I have just started programming a simple app to try different things out.
I was programming a ListView (and, in the same way a GridView) but there is something I got wrong. Each item is a couple of an image and a text field.
| img | __text__ |
I want to be able to choose any number of list items, keeping them enlightened for all the selection process, before passing the selected items to the next activity. If I want to
de-select one of them, I simply have to re-click on the item to have the selection disappear. For this purpose I use a custom selector so that when the item is pressed it changes colours.
If the items are all contained in a screen, everything is ok. But as soon as they grow in number and recycling kicks in, the enlightening of selected items which get out of the screen is lost. I have debugged the state of items and those whose enlightening is lost are still correctly selected, so I think it’s just a problem on how the graphic reloads when an item is restored after it went out of the device screen.
Here’s the code of the activity layout:
<!-- items_selection.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:orientation="vertical"
android:background="#color/Background">
<ListView
android:id="#+id/item_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/divider"
android:dividerHeight="3dp"
android:choiceMode="multipleChoice"
android:listSelector="#drawable/list_selector">
</ListView>
</LinearLayout>
This is the Row Item layout:
<!-- list_row.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/item_list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:padding="3dip" >
<ImageView
android:id="#+id/item_image"
android:layout_width="#dimen/img_side"
android:layout_height="#dimen/img_side" />
</LinearLayout>
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/item_list_item"
android:layout_centerVertical="true"
android:textColor="#color/black"
android:textSize="#dimen/textnorm"
/>
</RelativeLayout>
This is the selector I used:
<!-- list_selector.xml -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="#drawable/rect" />
<item
android:state_pressed="true"
android:drawable="#drawable/rect_sel" />
<item
android:state_selected="true"
android:state_pressed="false"
android:drawable="#drawable/rect_sel" />
</selector>
<!-- rect.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#D5DDE0"
android:centerColor="#e7e7e8"
android:endColor="#CFCFCF"
android:angle="270" />
</shape>
<!-- rect_sel.xml -->
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#78DDFF"
android:centerColor="#16cedb"
android:endColor="#09adb9"
android:angle="270" />
</shape>
This is the code of the Activity:
public class ItemSelection extends AppCompatActivity {
private int numitems;
private ListView listview;
private ArrayList<Item> items = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_selection);
numitems = 15;
build_list();
listview = (ListView) findViewById(R.id.item_list);
listview.setAdapter(new ListAdapter(this, items));
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.next_btn, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case R.id.next_btn:
Intent intent = new Intent (this, nextActivity.class);
intent.putStringArrayListExtra("items", Chosen_Items());
startActivity(intent);
return true;
default:
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
}
private void build_list() {
//Populates the item list with more items than the screen can support.
}
private ArrayList<String> Chosen_Items(){
ArrayList<String> selitems = new ArrayList<>();
for (int i=0; i<numitems; i++){
if (items.get(i).isSelected()){
selitems.add(items.get(i).getName());
}
}
return selitems;
}
This is the code of the listAdapter:
public class ListAdapter extends BaseAdapter {
private ArrayList <Item> items;
private Activity sActivity;
public ListAdapter(Activity sActivity, ArrayList<Item> items) {
this.sActivity = sActivity;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if(view == null) {
LayoutInflater li = sActivity.getLayoutInflater();
view = li.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.text = (TextView)view.findViewById(R.id.item_name);
holder.img = (ImageView)view.findViewById(R.id.item_image);
view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}
holder.text.setText(items.get(position).getName());
holder.img.setImageResource(items.get(position).getImage());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewitem) {
if (!viewitem.isSelected() && !items.get(position).isSelected()) {
viewitem.setSelected(true);
items.get(position).setSelected(true);
}
else {
viewitem.setSelected(false);
items.get(position).setSelected(false);
}
}
});
return view;
}
private static class ViewHolder{
public TextView text;
public ImageView img;
}
}
I have already tried to manually set the background color of the items re-entering the screen (by using
view.setBackgroundResource(R.drawable.rect_sel)
in the adapter, before the click handler) but the problem remains. Can anyone help me solving the problem?
~~~~~~~~~~~~~~~~~~~ SOLUTION ~~~~~~~~~~~~~~~~~~
It seems the selector doesn't follow the recycle of the items and their views.There has to be a better and more elegant solution taking advantage of a selector in this situation. But out of all the attempts i made, none has worked. This solution is the best workaround and does not use the selector.
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if(view == null) {
LayoutInflater li = sActivity.getLayoutInflater();
view = li.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.text = (TextView)view.findViewById(R.id.item_name);
holder.img = (ImageView)view.findViewById(R.id.item_image);
view.setTag(holder);
}
else {
holder = (ViewHolder)view.getTag();
}
holder.text.setText(items.get(position).getName());
holder.img.setImageResource(items.get(position).getImage());
if(items.get(position).isSelected()){
view.setBackgroundResource(R.drawable.rect_sel);
}else{
view.setBackgroundResource(R.drawable.rect);
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewitem) {
if (!viewitem.isSelected() && !items.get(position).isSelected()) {
viewitem.setBackgroundResource(R.drawable.rect_sel);
viewitem.setSelected(true);
items.get(position).setSelected(true);
}
else {
viewitem.setBackgroundResource(R.drawable.rect);
viewitem.setSelected(false);
items.get(position).setSelected(false);
}
}
});
return view;
}
private static class ViewHolder{
public TextView text;
public ImageView img;
}
While in the list_row.xml file, the following line can be just deleted:
android:background="#drawable/list_selector"
In your getView() method just add this test:
if (items.get(position).isSelected()){
view.setBackgroundResource(R.drawable.rect_sel);
} else {
view.setBackgroundResource(R.drawable.rect);
}
Or just view.setSelected(items.get(position).isSelected());. While you already have a selector for your list item.
You must define the current selection state of view inside getView method.
Add this line:
viewitem.setSelected(items.get(position).isSelected());
after viewholder has been created like:
holder.img.setImageResource(items.get(position).getImage());
viewitem.setSelected(items.get(position).isSelected());
I think you should set the id for your RelativeLayout then add it to ViewHolder
private static class ViewHolder{
public TextView text;
public ImageView img;
RelativeLayout rl;
}
After that you handle event when click RelativeLayout then change background for RelativeLayout
public View getView(...)
...
...
// you should update the state of relative layout first
if (items.get(position).isSelected()) {
holder.setBackgroundColor(Color.parseColor("#ffff00"));
}else{
holder.setBackgroundColor(Color.parseColor("#ff0000"));
}
holder.rl.setOnClickListener(new View.OnClickListener(){ //remmember it is rl.setOnClick... not view.setOnClick...
public void onClick(View v) {
if (!items.get(position).isSelected()) {
items.get(position).setSelected(true);
holder.setBackgroundColor(Color.parseColor("#ffff00"));
}else {
items.get(position).setSelected(false);
holder.setBackgroundColor(Color.parseColor("#ff0000"));
}
}
});
}
Suggestion
You should modify your row layout like this (I have removed LinearLayout but the new layout still good)
<!-- list_row.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/item_image"
android:layout_marginRight="5dip"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_width="#dimen/img_side"
android:layout_height="#dimen/img_side" />
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/item_image"
android:layout_centerVertical="true"
android:textColor="#color/black"
android:textSize="#dimen/textnorm"
/>
</RelativeLayout>
Remember that your list row layout is more simple then your listview will scroll faster, smooth and prevent some annoying bug.
Hope this help
I have a fragment that contains a GridView
<?xml version="1.0" encoding="utf-8"?>
<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" >
<GridView
android:padding="20dp"
android:id="#+id/sub_category_gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:horizontalSpacing="20dp"
android:numColumns="4"
android:verticalSpacing="10dp"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:fastScrollEnabled="true"
tools:listitem="#layout/sub_category_view" />
</LinearLayout>
Every child of this GridView contains one TextView and one ImageView
<?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:orientation="vertical"
android:gravity="center"
android:id="#+id/sub_category_view">
<ir.motorel.carbuyinstruduction.SquareLinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/button">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="#drawable/picture1"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:layout_margin="10dp"
android:id="#+id/sub_category_img"/>
</ir.motorel.carbuyinstruduction.SquareLinearLayout>
<TextView
android:layout_marginTop="5dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:gravity="center"
android:textColor="#C36518"
android:id="#+id/sub_category_name"/>
</LinearLayout>
When I fill GridView with Texts and Images, it's become very Laggy and slow when I scrolling. This is My adapter Class:
public class CustomGrid extends BaseAdapter{
private Context mContext;
public CustomGrid(Context c) {
mContext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return subCatTitle.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.sub_category_view, parent, false);
viewHolder = new ViewHolder();
viewHolder.subCatView = (LinearLayout) convertView.findViewById(R.id.sub_category_view);
viewHolder.subCatImg = (ImageView) convertView.findViewById(R.id.sub_category_img);
viewHolder.subCatTitle = (TextView) convertView.findViewById(R.id.sub_category_name);
//subCatImg.setImageResource(imgIDs.getResourceId(position, -1));
convertView.setTag(viewHolder);
}
else{
//imgIDs.recycle();
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.subCatTitle.setText(subCatTitle[position]);
return convertView;
}
}
public class ViewHolder{
public TextView subCatTitle;
public ImageView subCatImg;
public LinearLayout subCatView;
}
How can i optimize it to scroll more smoothly?
PS. My images are in drawable folder and their format is PNG.
I had a ImageView in my Activity's Header that I set a really big image to it. It was killing performance. There is no problem in GridView.
I am using Listview with custom Adapter and a selector which I have set as background of the listview row item parent layout. When I am not setting OnClick listener to the parent layout of the listview item, the selector is working fine and the row gets selected.
But as soon as I am setting OnClick listener to the parent layout of the listview item , the selector is not working. I don't want to use onItemClickListener as I have to take care of certain things from the ListView Adapter.
I have been searching for this for hours but didn't got any clue.
Please help.
Thanks
My Custom Adapter class
public class CustomAdapter extends BaseAdapter {
private final String[] mNotificationList;
private static LayoutInflater inflater = null;
private Activity mActivity;
public CustomAdapter(Activity activity,String[] data) {
mActivity = activity;
mNotificationList = data;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if(mNotificationList == null){
return 0;
}
else{
return mNotificationList.length;
}
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(final int position, View converterView, ViewGroup parent) {
if (converterView == null){
converterView = inflater.inflate(R.layout.notification_list_row, null);
}
NotificationListHolder listRowHolder = (NotificationListHolder)converterView.getTag();
if(listRowHolder==null) {
listRowHolder = new NotificationListHolder();
initializeView(listRowHolder,converterView);
}
bindView(listRowHolder,mNotificationList[position]);
return converterView;
}
private void bindView(NotificationListHolder listRowHolder, String notificationDetails) {
listRowHolder.articleName.setText(notificationDetails);
listRowHolder.parentLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mActivity, "TOAST",Toast.LENGTH_SHORT).show();
}
});
}
private void initializeView(NotificationListHolder listRowHolder,View converterView) {
listRowHolder.parentLayout = (LinearLayout) converterView.findViewById(R.id.notificationlist_row_layout);
listRowHolder.articleName = (TextView) converterView.findViewById(R.id.article_text);
converterView.setTag(listRowHolder);
}
public static class NotificationListHolder{
public LinearLayout parentLayout;
public TextView articleName;
}
}
list row item xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/notificationlist_row_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector" >
<TextView
android:id="#+id/article_text"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black"
android:textStyle="bold" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="40dp"
android:text="second view"
android:layout_below="#+id/article_text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black"
android:textStyle="bold" />
</RelativeLayout>
list selector xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#color/msg_read_bg" />
<item
android:state_pressed="true"
android:drawable="#color/msg_read_bg" />
<item
android:state_activated="true"
android:drawable="#color/msg_read_bg" />
<item
android:state_active="true"
android:drawable="#color/msg_read_bg" />
<item
android:state_focused="true"
android:drawable="#color/msg_read_bg" />
<item android:drawable="#android:color/white" />
</selector>
I want to make an app with a interface like google+ or evernote like the following , how to perform these ui? Use GridView in Android?
They are similar to that. But they have their own term called DashBoard.
Here is a link on a tutorial,
DashBoard..
Here is a link which explains few things to you,
http://android-developers.blogspot.in/2010/05/twitter-for-android-closer-look-at.html
And also this question here, which was previously discussed about it,
Android Dashboard Pattern
And this looks to be the suggested way to do it,
<com.google.android.apps.iosched.ui.widget.DashboardLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="#+id/home_btn_schedule"
style="#style/DashboardButton"
android:text="#string/btn_schedule"
android:drawableTop="#drawable/home_btn_schedule" />
<Button android:id="#+id/home_btn_map"
style="#style/DashboardButton"
android:text="#string/btn_map"
android:drawableTop="#drawable/home_btn_map" />
<Button android:id="#+id/home_btn_sessions"
style="#style/DashboardButton"
android:text="#string/btn_sessions"
android:drawableTop="#drawable/home_btn_sessions" />
<Button android:id="#+id/home_btn_starred"
style="#style/DashboardButton"
android:text="#string/btn_starred"
android:drawableTop="#drawable/home_btn_starred" />
<Button android:id="#+id/home_btn_vendors"
style="#style/DashboardButton"
android:text="#string/btn_vendors"
android:drawableTop="#drawable/home_btn_vendors" />
<Button android:id="#+id/home_btn_announcements"
style="#style/DashboardButton"
android:text="#string/btn_announcements"
android:drawableTop="#drawable/home_btn_announcements" />
Taken From Here..
public class Dashboard extends Activity
implements OnItemClickListener {
Context con;
static LauncherIcon[] ICONS = {
new LauncherIcon(R.drawable.breakfasdd, "text1"),
new LauncherIcon(R.drawable.lunch, "text2"),
new LauncherIcon(R.drawable.dinner1, "text3"),
new LauncherIcon(R.drawable.syn1, "text4"),
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
GridView gridview = (GridView) findViewById(R.id.dashboard_grid);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(this);
}
static class LauncherIcon {
final String text;
final int imgId;
public LauncherIcon(int imgId, String text) {
super();
this.imgId = imgId;
this.text = text;
}
}
static class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return ICONS.length;
}
#Override
public LauncherIcon getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
static class ViewHolder {
public ImageView icon;
public TextView text;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.dashboard_icon, null);
holder = new ViewHolder();
holder.text = (TextView) v
.findViewById(R.id.dashboard_icon_text);
holder.icon = (ImageView) v
.findViewById(R.id.dashboard_icon_img);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.icon.setImageResource(ICONS[position].imgId);
holder.text.setText(ICONS[position].text);
return v;
}
}
and to get item selected
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
int pos = position;{
}
dashboard_icon.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:orientation="vertical" >
<ImageView
android:id="#+id/dashboard_icon_img"
android:layout_width="fill_parent"
android:layout_height="96.0dip"
android:scaleType="fitCenter" />
<TextView
android:id="#+id/dashboard_icon_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20.0dip"
android:layout_marginTop="2.0dip"
android:gravity="center"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#android:color/black" />
</LinearLayout>
dashboard.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="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"
android:text="BACK" />
<GridView
android:id="#+id/dashboard_grid"
style="#style/dashboard"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:listSelector="#android:color/transparent"
android:stretchMode="columnWidth"
android:verticalSpacing="20.0dip" />
</RelativeLayout>
I'm trying to customize a ListView to have a default background image and highlighted background image for each single row.
However, the highlighted background image affects single rows, and the default background image affects the whole ListView; but I need it to affect each single row.
Could somebody tell me how to do this?
This is my code:
layout/main.xml:
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dip"
android:listSelector="#drawable/bg_highlighted"
/>
drawable/selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/bg_default"/>
<item android:state_focused="true" android:drawable="#drawable/bg_default"/>
</selector>
src/main.java:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,R.layout.list, mStrings); /*"Item1","Item2","Item3","Item4"*/
ListView lv = (ListView)findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setBackgroundResource(R.drawable.selector);
As default background and highlighted background I use png images.
This is what I have, but this is what I want.
I did like heepie advised above. And as I understand there is not a property that allow to set background drawable to single row of ListView directly. It's should be done by creating custom view in getView method of a custom adapter. This is my final code. May be it will be useful to someone.
layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/my_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
layout/my_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="left|center_vertical"
android:paddingLeft="6dip"
android:textColor="#FFFFFF"
android:background="#drawable/list_selector"
/>
drawable/list_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#drawable/bg_highlighted" />
<item android:drawable="#drawable/bg_default" />
</selector>
Drawable png images:
drawable/bg_default.png:
drawable/bg_highlighted.png:
src/main.java:
public class main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyAdapter adapter;
ArrayList<String> mStrings = new ArrayList<String>();
mStrings.add("Item 1");
mStrings.add("Item 2");
mStrings.add("Item 3");
mStrings.add("Item 4");
ListView lv = (ListView) findViewById(R.id.my_list);
adapter = new MyAdapter(this, mStrings);
lv.setAdapter(adapter);
}
}
src/MyAdapter.java:
public class MyAdapter extends BaseAdapter {
public Activity activity;
ArrayList<String> data = new ArrayList<String>();
private static LayoutInflater inflater = null;
public MyAdapter(Activity a, ArrayList<String> d) {
activity = a;
data = d;
inflater = LayoutInflater.from(activity);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.my_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Touch on view handle
Log.d("", "Touched row "+position);
}
});
//customizing view
holder.textView = (TextView)convertView.findViewById(R.id.my_textview);
holder.textView.setText(data.get(position));
return convertView;
}
public static class ViewHolder {
public TextView textView;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
}
And this is a result:
Instead of using arrayadapter would probably be better using a new class extending baseadapter and changing the background of each row from the getview method
The problem I see is you're actually using the item selector as the entire ListView background here:
lv.setBackgroundResource(R.drawable.selector);
All you have to do is to set this selector as the background of the root view inside your layout/list.xml (the layout inflated for each item in the list)