How to set rounded background for list popup window? - android

I have a menu which has sharp rectangle background. I have tried a lot i can't change it to rounded background.
popup_menu.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#1F2026"
android:orientation="horizontal"
>
<TextView
android:id="#+id/details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:fontFamily="#font/quicksand_regular"
android:text="#string/add_to_favourite"
android:textColor="#color/icon_color_dark" />
</LinearLayout>
The above given is my popup menu xml.
public static void showAlbumPopupOptions(final Activity activity, ImageView listMore,
final Song song, String songId, int playingState) {
final boolean isLogged = AppController.getBooleanPreference(Constants.LOGGED_IN, false);
String[] listItems;
listItems = activity.getResources().getStringArray(R.array.popup_menu_add_album);
ArrayAdapter<String> mPopupAdapter = new ArrayAdapter<>(activity, R.layout.popup_menu, R
.id.details, listItems);
final ListPopupWindow albumPopup = new ListPopupWindow(activity);
albumPopup.setContentWidth(Utils.measureContentWidth(mPopupAdapter, activity));
albumPopup.setAdapter(mPopupAdapter);
albumPopup.setHeight(ListPopupWindow.WRAP_CONTENT);
albumPopup.setAnchorView(listMore);
albumPopup.setModal(true);
albumPopup.setDropDownGravity(Gravity.END);
final LoadingProgressDialog loadingProgressDialog = new LoadingProgressDialog(activity, R
.style
.DialogThemeProgress, false);
albumPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
if (isLogged) {
DialogPlayList dialogPlayList = new DialogPlayList(activity,
activity, String.valueOf(song.getId()), loadingProgressDialog);
dialogPlayList.show();
loadingProgressDialog.setDimDialog(false);
loadingProgressDialog.showProgress();
} else {
redirectLogin(activity);
}
albumPopup.dismiss();
} else if (position == 2) {
showAudioShare(song, activity);
albumPopup.dismiss();
} else if (position == 1) {
AppController.addToQueueSongs(activity, song, songId,
playingState);
albumPopup.dismiss();
}
}
});
albumPopup.show();
}
The above given method is called when user clicks the more option in the list. I am adding datas to the list from this method. As a result I am getting this.
But actually what I want is - image given below.
I have tried setting background as rounded corners but no use. I literally have no idea how to achieve. Please suggest me some solutions. Thanks in advance.

With the a Material Components Theme you have a default rounded background with a corner radius of 4dp.
You can customize it using the listPopupWindowStyle attribute in your app theme:
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
<item name="listPopupWindowStyle">#style/myListPopupWindow</item>
</style>
with:
<style name="myListPopupWindow" parent="Widget.MaterialComponents.PopupMenu.ListPopupWindow">
<item name="android:popupBackground">#drawable/popupMenuBackground</item>
</style>
where the drawable background is something like:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="?attr/colorSurface"/>
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp"/>
<padding
android:bottom="8dp"
android:top="8dp"/>
</shape>

I found the answer. Add this code with ListPopupWindow before setting the adapter.
Drawable background = ContextCompat.getDrawable(activity, R.drawable
.res_black_menuroundfilled_corner);
albumPopup.setBackgroundDrawable(background);
Remove android:background="#1F2026" in popup_menu.xml
Below given code is for drawable file. res_black_menuroundfilled_corner
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#1F2026"/>
<corners android:radius="15dp"/>
</shape>

ListPopupWindow listPopupWindow = new ListPopupWindow(this);
listPopupWindow.setAdapter(popUpAdapter);
listPopupWindow.setAnchorView(itemView);
listPopupWindow.setDropDownGravity(Gravity.NO_GRAVITY);
listPopupWindow.setBackgroundDrawable(ContextCompat.getDrawable(this,R.drawable.round_corner));
listPopupWindow.setWidth(ListPopupWindow.WRAP_CONTENT);
listPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
listPopupWindow.show();

Related

How to make a View looks like it is being selected programmatically, if background is ?android:attr/selectableItemBackground (ListView in AlertDialog)

I pretty like the selector behavior generated in navigation drawer.
It has ripple effect.
Its ImageView and TextView has proper color, when being selected.
In my dialog, I try to achieve the same effect, by using the following layout.
label_array_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="?android:attr/selectableItemBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<ImageView
android:duplicateParentState="true"
android:id="#+id/image_view"
android:paddingStart="24dp"
android:paddingLeft="24dp"
android:paddingEnd="16dp"
android:paddingRight="16dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="?attr/labelIconSelector" />
<TextView
android:duplicateParentState="true"
android:textSize="16sp"
android:id="#+id/text_view"
android:layout_width="0dp"
android:width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textColor="?attr/labelTextViewColorSelector" />
</LinearLayout>
labelIconSelector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true">
<bitmap android:src="#drawable/ic_label_white_24dp"
android:tint="#color/colorPrimaryBrown" />
</item>
<item>
<bitmap android:src="#drawable/ic_label_white_24dp"
android:tint="#ff757575" />
</item>
</selector>
labelTextViewColorSelector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#color/colorPrimaryBrown" />
<item android:color="#color/primaryTextColorLight" />
</selector>
In my ArrayAdapter, I try to programmatically select the 1st item via view.setSelected(true)
public class LabelArrayAdapter extends ArrayAdapter<TabInfo> {
private static class ViewHolder {
public final ImageView imageView;
public final TextView textView;
public ViewHolder(View view) {
imageView = view.findViewById(R.id.image_view);
textView = view.findViewById(R.id.text_view);
Utils.setCustomTypeFace(textView, Utils.ROBOTO_REGULAR_TYPE_FACE);
}
}
public LabelArrayAdapter(#NonNull Context context, List<TabInfo> tabInfos) {
super(context, R.layout.label_array_adapter, tabInfos);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(this.getContext());
view = inflator.inflate(R.layout.label_array_adapter, null);
final ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
// Not sure why this is required.
view.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, Utils.dpToPixel(48)));
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
TabInfo tabInfo = getItem(position);
if (tabInfo == null) {
holder.imageView.setVisibility(View.INVISIBLE);
holder.textView.setText("(No label)");
} else {
holder.imageView.setVisibility(View.VISIBLE);
holder.textView.setText(tabInfo.getName());
}
if (position == 0) {
view.setSelected(true);
} else {
view.setSelected(false);
}
return view;
}
}
This is how I try to show Dialog via DialogFragment.
return new AlertDialog.Builder(getActivity())
.setTitle("Move to")
.setAdapter(new LabelArrayAdapter(this.getContext(), customTabInfos), (dialog, which) -> {
})
.create();
However, it doesn't work as you can see in the following screenshot. The 1st item doesn't look like it is being selected.
May I know, is there anything I had missed out?
How to make a View looks like it is being selected programmatically, if its background is ?android:attr/selectableItemBackground (ListView in AlertDialog)
Update
Using
alertDialog.getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
alertDialog.getListView().setSelection(position);
wouldn't help either.
Here is an approach using a layer list drawable as the background for the view group that represents the item being selected.
First, for API 21+, we define a layer list drawable that displays the selected color when the item is selected. A call to View#setSelected() must be made for this to have an effect.
layer_list.xml (v21)
color/selected is #2000ffe5 for the demos.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<selector>
<item
android:drawable="#color/selected"
android:state_selected="true" />
</selector>
</item>
<item
android:id="#+id/selectableBackground"
android:drawable="?android:selectableItemBackground" />
</layer-list>
For API < 21, we cannot use android:drawable="?android:selectableItemBackground" in the layer list, so we will fall back to an alternate but similar visual cue.
layer_list < API 21
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<selector android:exitFadeDuration="#android:integer/config_shortAnimTime">
<item
android:drawable="#color/selected"
android:state_pressed="false"
android:state_selected="true" />
<item
android:drawable="#color/selectable_background"
android:state_pressed="true" />
</selector>
</item>
</layer-list>

Android: Add divider between items in RecyclerView

I am using RecyclerView with rounded corner, to make it rounded corner I used below XML:
view_rounded.xml:-
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#008f8471"/>
<stroke android:width="2dp" android:color="#ffffff" />
<corners android:radius="10dp"/>
</shape>
fragment_main.xml:-
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/view_rounded"/>
adapter_main.xml:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textTitle"
style="#style/AppTheme.ListTextView"
/>
</LinearLayout>
style.xml:-
<style name="AppTheme.ListTextView" parent="android:Widget.Material.TextView">
<item name="android:gravity">left</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textAllCaps">false</item>
<item name="android:padding">10dp</item>
<item name="android:textAppearance">#android:style/TextAppearance.DeviceDefault.Medium</item>
<item name="android:textColor">#color/tabsScrollColor</item>
<item name="android:textStyle">bold</item>
</style>
Getting (without item separator):
Required (with item separator):
you should try add Divider
mListview.addItemDecoration(new DividerItemDecoration(this.getActivity(), LinearLayout.VERTICAL));
I have done this way:
onCreateView() of Fragment:
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
SimpleDividerItemDecoration.java:
public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
public SimpleDividerItemDecoration(Context context) {
mDivider = context.getResources().getDrawable(R.drawable.recycler_horizontal_divider);
}
#Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = parent.getPaddingLeft();
int right = parent.getWidth() - parent.getPaddingRight();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
recycler_horizontal_divider.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp" />
<solid android:color="#2EC590" />
</shape>
Hope this will help you.
RecyclerView works different from ListViews. You need to add ItemDecorators for the recycler view. As the docs says,
An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set. This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more.
Take a look into this link : https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ItemDecoration.html
Well what I did to achieve this is, I first created layout for my adapter row as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:id="#+id/lineView"
android:layout_width="match_parent"
android:layout_height="2px"
android:background="#android:color/black"/>
<TextView
android:id="#+id/textTitle"
style="#style/AppTheme.ListTextView"
/>
</LinearLayout>
Then in my adapter I checked for first row and changed its viewLine Visibility to invisible
#Override
public void onBindViewHolder(ChildInfoViewHolder holder, final int position) {
if(position == 0){
holder.viewLine.setVisibility(View.INVISIBLE);
}
//...
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
protected View viewLine;
public ChildInfoViewHolder(View view) {
super(view);
viewLine = view.findViewById(R.id.viewLine);
//...
}
}
To add dividers to your recyclerview you need to use decorator - https://gist.github.com/alexfu/0f464fc3742f134ccd1e after you add that to your project add a line
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
This line of code worked for me:
recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL));
For vertical line, pass second argument as DividerItemDecoration.VERTICAL.
Set the selector at the background of the list item in your layout if you are using custom adapter
Try this one:
A very nice solution by Michel-F. Portzert
public class ClippedListView extends ListView {
public ClippedListView(Context context) {
super(context);
}
public ClippedListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void dispatchDraw(Canvas canvas) {
float radius = 10.0f;
Path clipPath = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.dispatchDraw(canvas);
}
}
Try This From
Reference
Android: ListView with rounded corners
First off, we need the drawables for the backgrounds of the Lists entries:
For the entries in the middle of the list, we don't need rounded corners, so create a xml in your drawable folder "list_entry_middle.xml" with following content:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<stroke android:width="1px" android:color="#ffbbbbbb" />
</shape>
</item>
<item android:bottom="1dp" android:left="1dp" android:right="1dp">
<shape >
<solid android:color="#ffffffff" />
</shape>
</item>
</layer-list>
For the rounded corners, create another xml, "rounded_corner_top.xml":
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<stroke android:width="1dp" android:color="#ffbbbbbb" />
<corners android:topLeftRadius="20dp"
android:topRightRadius="20dp"
/>
</shape>
</item>
<item android:top="1dp" android:left="1dp" android:right="1dp" android:bottom="1dp">
<shape >
<solid android:color="#ffffffff" />
<corners android:topLeftRadius="20dp"
android:topRightRadius="20dp"
/>
</shape>
</item>
</layer-list>
Implementing the bottom part is quite the same, just with bottomLeftRadius and bottomRightRadius. (maybe also create one with all corners rounded, if the list only has one entry)
For better usability, also provide drawables with other colors for the different states, that the list item can have and reference them in another xml in the drawable folder ("selector_rounded_corner_top.xml") as followed:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/rounded_corner_top_click"
android:state_pressed="true" />
<item android:drawable="#drawable/rounded_corner_top_click"
android:state_focused="true" />
<item android:drawable="#drawable/rounded_corner_top" />
</selector>
Now do the same for the other backgrounds of the list.
All that is left now, is to assign the right backgrounds in our ListAdapter like following:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//...
//skipping the view reuse stuff
if (position == 0 && entry_list.size() == 1) {
view.setBackgroundResource(R.drawable.selector_rounded_corner);
} else if (position == 0) {
view.setBackgroundResource(R.drawable.selector_rounded_corner_top);
} else if (position == entry_list.size() - 1) {
view.setBackgroundResource(R.drawable.selector_rounded_corner_bottom);
} else {
view.setBackgroundResource(R.drawable.selector_middle);
}
//...
//skipping the filling of the view
}
Modify your ListView like below.Add the list_bg as the background of your ListView Also specify some padding for the top and the bottom of the listView otherwise the 1st and the last item in the list will overlap with the rounded corners showing rectangular corners.
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#drawable/list_bg"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:fastScrollEnabled="true"
android:choiceMode="singleChoice" />
Use this drawable xml for curve shape listview and set background to your list view or any layout:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="6dp" />
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
</shape>
Try this
custom_rounded_list.xml :
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#ff2521"
android:endColor="#2f5511"
android:angle="270"/>
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp" />
</shape>
Your listview:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mylst"
android:background="#drawable/custom_rounded_list" />
you are setting list_selector for both textview and listview background. Use list_selector only for listview and if you want hover effect on textview too, then create another list_selector_textview which haven't include the <corners android:radius="10dp" property.
The problem is because you are setting the background with corners not only to the list view, but also to the item. You should make separate backgrounds for item (with selector) and one for list view with corners.
list_bg.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#008f8471"/>
<stroke android:width="1dip" android:color="#ffffff" />
<corners android:radius="10dp"/>
<padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>
Now you can setup this drawable as the background of your list view.
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#drawable/list_bg.xml"
android:fastScrollEnabled="true"
android:choiceMode="singleChoice" />
And for list view item you can use selector to have hover functionality:
list_item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/list_item_selected" android:state_pressed="true"/>
<item android:drawable="#drawable/list_item_selected" android:state_pressed="false" android:state_selected="true"/>
<item android:drawable="#android:color/transparent"/>
Where list_item_selected is :
list_item_selected.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#4d8f8471"/>
<stroke android:width="1dip" android:color="#ffffff" />
</shape>
And after that you can setup this selector to the item in your xml:
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_item_selector" />
So your list view will have always same background with corners, and the background of items of list view, will be without corners and will be changed in pressed or selected state.
Just One Line...
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
That's all
Try this
recyclerView.apply {
....
addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
}

RecyclerView highlight item on click

I created the following RecyclerView dynamically. I want to highlight the clicked item while clicking in it. After click, it goes to the next Activity. I have given the background XML below:
hRecyclerView.setBackgroundResource(R.drawable.mylistview_background);
Is this not the way to set it? What should I do here?
hRecyclerView = (RecyclerView) findViewById(R.id.my_history_view);
// use a linear layout manager
hLayoutManager = new LinearLayoutManager(this);
hRecyclerView.setLayoutManager(hLayoutManager);
hRecyclerView.setVerticalScrollBarEnabled(false);
hRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
hRecyclerView.setBackgroundResource(R.drawable.mylistview_background);
hAdapter = new HistoryAdapter(history, this);
hRecyclerView.setAdapter(hAdapter);
hRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// do whatever
if(position>0) {
History his = history.get(position - 1);
Intent intent = new Intent(getApplicationContext(), TrackActivity.class);
intent.putExtra("from", his.src_station);
intent.putExtra("to", his.dest_station);
intent.putExtra("train_no", his.train_no);
intent.putExtra("train_name", his.train_name);
startActivity(intent);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
}
})
);
hRecyclerView.setItemAnimator(new DefaultItemAnimator());
mylistview_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<gradient android:endColor="#22000000" android:startColor="#a7a2288f" android:angle="270" />
</shape>
</item>
<item android:state_focused="true">
<shape>
<gradient android:endColor="#2200ff00" android:startColor="#a2008f00" android:angle="270" />
</shape>
</item>
</selector>
Any help is much Appreciated!
You are setting the background of your entire RecyclerView (Which doesn't get 'selected'). You need to be setting the background of your row view. In onCreateViewHolder in HistoryAdapter, you'll be inflating the row view. THAT is the background that needs to have a selector drawable (You can set it in the xml, or in code).
hRecyclerView.setBackgroundResource(R.drawable.mylistview_background);
First delete this line, it's for the entire recyclerview.
Your custom row / item layout should look like this (put mylistview_background.xml in the drawable folder ) :
<RelativeLayout ...
android:background="#drawable/mylistview_background">...
</RelativeLayout>

Change background color of selected item on a ListView

I want to know on how I can change the background color of the selected item on my listView. I only want to change the specific item clicked by the user, meaning if the user clicks another item it will be the one which is highlighted. Well since I want it to keep simple as possible and use the default android listview I used this code instead:
record_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
try{
for (int ctr=0;ctr<=record_items.length;ctr++){
if(i==ctr){
record_list.getChildAt(ctr).setBackgroundColor(Color.CYAN);
}else{
record_list.getChildAt(ctr).setBackgroundColor(Color.WHITE);
}
}
}
catch (Exception e){
e.printStackTrace();
}
Log.v("Selected item",record_list.getItemAtPosition(i));
}
});
Ok this one is working but the problem is that it's slow. Now I want to know if there's any other way around that I can do which will give the same output as I made.
I tried using record_list.getSelectedView().setBackgroundColor(Color.CYAN); but it gives me a null pointer exception.
I also tried the selector.xml but it also didn't do the trick.
Furthermore, there is one properties here on ListView which is called listSelector. It's a drawable as said by the documentation "Drawable used to indicate the currently selected item in the list." I also believe that this should do the trick and yes it do the trick on my emulator but not on my galaxy tab. I also tried the other methods but nothing works as I wanted it to be.
You can keep track the position of the current selected element:
OnItemClickListener listViewOnItemClick = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
mSelectedItem = position;
mAdapter.notifyDataSetChanged();
}
};
And override the getView method of your adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view = View.inflate(context, R.layout.item_list, null);
if (position == mSelectedItem) {
// set your color
}
return view;
}
For me it did the trick.
You can use a selector. Change the colors values and modify the below according to your needs.
bkg.xml in drawable folder
<?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/pressed" />
<item android:state_focused="false"
android:drawable="#drawable/normal" />
</selector>
pressed.xml in drawable folder
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FF1A47"/> // color
<stroke android:width="3dp"
android:color="#0FECFF"/> // border
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners android:bottomRightRadius="7dp" // for rounded corners
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
normal.xml in drawable folder
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke android:width="3dp"
android:color="#0FECFF" />
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
Set the background drawable to listview custom layout to be inflated for each row
I recommend using a custom listview with a custom adapter.
android:background="#drawable/bkg"
If you have not used a custom adapter you can set the listselector to listview as below
android:listSelector="#drawable/bkg"
Define variable
private ListView mListView;
Initialize variable
mListView = (ListView)findViewById(R.id.list_view);
OnItemClickListener of listview
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adpterView, View view, int position,
long id) {
for (int i = 0; i < mListView.getChildCount(); i++) {
if(position == i ){
mListView.getChildAt(i).setBackgroundColor(Color.BLUE);
}else{
mListView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
}
}
});
Build and run the project - Done
If you want to have the item remain highlighted after you have clicked it, you need to manually set it as being selected in the onItemClick listener
Android ListView selected item stay highlighted:
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true); // <== Will cause the highlight to remain
//... do more stuff
}});
This assumes you have a state_selected item in your selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_pressed="true" android:drawable="#color/red" />
<item android:state_enabled="true" android:state_focused="true" android:drawable="#color/red" />
<item android:state_enabled="true" android:state_selected="true" android:drawable="#color/red" />
<item android:drawable="#color/white" />
</selector>
Method 1:
Update ListView in the your xml layout activity/fragment:
<ListView
...
android:choiceMode="singleChoice"
android:listSelector="#android:color/darker_gray"
/>
That's it, you're done!
If you want a programmatic way to handle this then use method 2...
Method 2:
If you're using a ListFragment you can override onListItemClick(), using the view to set the colour. Save the current View selected to reset the colour of the last selection.
Please note, this only works on listviews that fit on one screen, as the view is recycled.
public class MyListFragment extends ListFragment {
View previousSelectedItem;
...
#Override
public void onListItemClick(ListView parent, View v, int position, long id) {
super.onListItemClick(parent, v, position, id);
if (previousSelectedItem!=null) {
previousSelectedItem.setBackgroundColor(Color.WHITE);
}
previousSelectedItem=v;
v.setBackgroundColor(Color.BLUE);
}
}
First you can create selector xml file like below in your drawable folder drawable/list_item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true">
<shape android:shape="rectangle">
<solid android:color="#333333" />
<padding android:left="5dp" android:right="5dp" />
</shape></item>
<item><shape android:shape="rectangle">
<solid android:color="#222222" />
</shape></item>
</selector>
And then in your listview specify background as
android:background="#drawable/list_item_selector"
For those wondering what EXACTLY needs to be done to keep rows selected even as you scroll up down. It's the state_activated The rest is taken care of by internal functionality, you don't have to worry about toggle, and can select multiple items. I didn't need to use notifyDataSetChanged() or setSelected(true) methods.
Add this line to your selector file, for me drawable\row_background.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="#android:color/holo_blue_light"/>
<item android:state_enabled="true" android:state_pressed="true" android:drawable="#android:color/holo_blue_light" />
<item android:state_enabled="true" android:state_focused="true" android:drawable="#android:color/holo_blue_bright" />
<item android:state_enabled="true" android:state_selected="true" android:drawable="#android:color/holo_blue_light" />
<item android:state_activated="true" android:drawable="#android:color/holo_blue_light" />
<item android:drawable="#android:color/transparent"/>
</selector>
Then in layout\custom_row.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="wrap_content"
android:padding="10dip"
android:background="#drawable/row_background"
android:orientation="vertical">
<TextView
android:id="#+id/line1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
For more information, I'm using this with ListView Adapter, using
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
and
myList.setMultiChoiceModeListener(new MultiChoiceModeListener()...
from this example: http://www.androidbegin.com/tutorial/android-delete-multiple-selected-items-listview-tutorial/
Also, you (should) use this structure for your list-adapter coupling: List myList = new ArrayList();
instead of: ArrayList myList = new ArrayList();
Explanation: Type List vs type ArrayList in Java
Simplest way I've found:
in your activity XML add these lines:
<ListView
...
android:choiceMode="singleChoice"
android:listSelector="#666666"
/>
or programatically set these properties:
listView.setSelector(Drawable selector)
listView.setSelector(int resourceId)
My particular example:
<ListView
android:choiceMode="singleChoice"
android:listSelector="#666666"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"/>
thanks to AJG:
https://stackoverflow.com/a/25131125/1687010
View updateview;// above oncreate method
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (updateview != null)
updateview.setBackgroundColor(Color.TRANSPARENT);
updateview = view;
view.setBackgroundColor(Color.CYAN);
}
});
I'm also doing the similar thing: highlight the selected list item's background (change it to red) and set text color within the item to white.
I can think out a "simple but not efficient" way:
maintain a selected item's position in the custom adapter, and change it in the ListView's OnItemClickListener implement:
// The OnItemClickListener implementation
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListViewAdapter.setSelectedItem(position);
}
// The custom Adapter
private int mSelectedPosition = -1;
public void setSelectedItem (int itemPosition) {
mSelectedPosition = itemPosition;
notifyDataSetChanged();
}
Then update the selected item's background and text color in getView() method.
// The custom Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
if (position == mSelectedPosition) {
// customize the selected item's background and sub views
convertView.setBackgroundColor(YOUR_HIGHLIGHT_COLOR);
textView.setTextColor(TEXT_COLOR);
} else {
...
}
}
After searching for a while, I found that many people mentioned about to set android:listSelector="YOUR_SELECTOR". After tried for a while, I found the simplest way to highlight selected ListView item's background can be done with only two lines set to the ListView's layout resource:
android:choiceMode="singleChoice"
android:listSelector="YOUR_COLOR"
There's also other way to make it work, like customize activatedBackgroundIndicator theme. But I think that would be a much more generic solution since it will affect the whole theme.
use the below xml as listitem background it will solve all the issues.
The selected will be highlighted though you scrolled down.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_orange_dark" android:state_pressed="true"/>
<item android:drawable="#android:color/holo_green_light" android:state_selected="true"/>
<item android:drawable="#android:color/holo_green_light" android:state_activated="true"/>
Thanks,
Nagendra
I know this is a old question, but i give a simple solution for this need (without loops!):
//On your adapter create a variable:
private View lastSelectedItem;
//Define the folowing method:
private void toggleBackgroundItem(View view) {
if (lastSelectedItem != null) {
lastSelectedItem.setBackgroundColor(Color.TRANSPARENT);
}
view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
lastSelectedItem = view;
}
//finally invoque the method onItemClick
lvSac.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){
toggleBackgroundItem(view);
}
}
In a ListView set:
android:choiceMode="singleChoice"
Create a selector for a background (drawable/selector_gray.xml):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/gray" android:state_checked="true" />
<item android:drawable="#color/white" />
</selector>
Add an item for a list:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp"
android:background="#drawable/selector_gray"
android:textColor="#color/colorPrimary"
tools:text="Your text" />
In a ViewHolder you can inflate this item.
nameofList.getChildAt(position).setBackgroundColor(RED);
worked for me
assume you want one item to be clicked each time. Then this code works well. Let's take the listview name as stlist
stList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
// here i overide the onitemclick method in onitemclick listener
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//color change
//selected item colored
for(int i=0; i<stList.getAdapter().getCount();i++)
{
stList.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
parent.getChildAt(position).setBackgroundColor(Color.GRAY);
});
This is a simple method that can handle selection even if the list is long as well:
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.list_item, null);
//Handle your items.
//StringHolder.mSelectedItem is a public static variable.
if(getItemId(position)==StringHolder.mSelectedItem){
rowView.setBackgroundColor(Color.LTGRAY);
}else{
rowView.setBackgroundColor(Color.TRANSPARENT);
}
return rowView;
}
And then in your onclicklistener:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1);
catagoryAdapter.notifyDataSetChanged();
.....
It's very simple. In the constructor of the "OnItemClick" use the parameter "view" which is the second one that represents the listView or GridView's items's view and it becomes the new item's view made by the adapterView it self. So to set new color ONLY to the SELECTED ITEM itself do as the following:
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
//view is instead of the view like textView , ImageView, or whatever
view.setBackgroundColor(Color.green);
}
If you do any different codes to set new color, you will face awkward behaviours like the green color will be applied to the unclicked item.

How do I create a ListView with rounded corners in Android?

How do I create a ListView with rounded corners in Android?
Here is one way of doing it (Thanks to Android Documentation though!):
Add the following into a file (say customshape.xml) and then place it in (res/drawable/customshape.xml)
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#SomeGradientBeginColor"
android:endColor="#SomeGradientEndColor"
android:angle="270"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
Once you are done with creating this file, just set the background in one of the following ways:
Through Code:
listView.setBackgroundResource(R.drawable.customshape);
Through XML, just add the following attribute to the container (ex: LinearLayout or to any fields):
android:background="#drawable/customshape"
Hope someone finds it useful...
Although that did work, it took out the entire background colour as well. I was looking for a way to do just the border and just replace that XML layout code with this one and I was good to go!
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
</shape>
#kris-van-bael
For those having issues with selection highlight for the top and bottom row where the background rectangle shows up on selection you need to set the selector for your listview to transparent color.
listView.setSelector(R.color.transparent);
In color.xml just add the following -
<color name="transparent">#00000000</color>
Update
The solution these days is to use a CardView with support for rounded corners built in.
Original answer*
Another way I found was to mask out your layout by drawing an image over the top of the layout. It might help you. Check out Android XML rounded clipped corners
The other answers are very useful, thanks to the authors!
But I could not see how to customise the rectangle when highlighting an item upon selection rather than disabling the highlighting #alvins #bharat dojeha.
The following works for me to create a rounded list view item container with no outline and a lighter grey when selected of the same shape:
Your xml needs to contain a selector such as e.g. ( in res/drawable/customshape.xml):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke android:width="8dp" android:color="#android:color/transparent" />
<padding android:left="14dp" android:top="14dp"
android:right="14dp" android:bottom="14dp" />
<corners android:radius="10dp" />
<gradient
android:startColor="#android:color/background_light"
android:endColor="#android:color/transparent"
android:angle="225"/>
</shape>
</item>
<item android:state_pressed="false">
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke android:width="8dp" android:color="#android:color/transparent" />
<padding android:left="14dp" android:top="14dp"
android:right="14dp" android:bottom="14dp" />
<corners android:radius="10dp" />
<gradient
android:startColor="#android:color/darker_gray"
android:endColor="#android:color/transparent"
android:angle="225"/>
</shape>
</item>
Then you need to implement a list adapter and override the getView method to set the custom selector as background
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//snip
convertView.setBackgroundResource(R.drawable.customshape);
//snip
}
and need to also 'hide' the default selector rectangle e.g in onCreate (I also hide my thin grey divider line between the items):
listView.setSelector(android.R.color.transparent);
listview.setDivider(null);
This approach solves a general solution for drawables, not just ListViewItem with various selection states.
Yet another solution to selection highlight problems with first, and last items in the list:
Add padding to the top and bottom of your list background equal to or greater than the radius. This ensures the selection highlighting doesn't overlap with your corner curves.
This is the easiest solution when you need non-transparent selection highlighting.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#color/listbg" />
<stroke
android:width="2dip"
android:color="#D5D5D5" />
<corners android:radius="10dip" />
<!-- Make sure bottom and top padding match corner radius -->
<padding
android:bottom="10dip"
android:left="2dip"
android:right="2dip"
android:top="10dip" />
</shape>
actually, i think the best solution is described on this link:
http://blog.synyx.de/2011/11/android-listview-with-rounded-corners/
in short, it uses a different background for the top, middle and bottom items, so that the top and bottom ones would be rounded.
This was incredibly handy to me. I would like to suggest another workaround to perfectly highlight the rounded corners if you are using your own CustomAdapter.
Defining XML Files
First of all, go inside your drawable folder and create 4 different shapes:
shape_top
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
shape_normal
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
shape_bottom
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:bottomRightRadius="10dp"
android:bottomRightRadius="10dp"/>
shape_rounded
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomRightRadius="10dp"
android:bottomRightRadius="10dp"/>
Now, create a different row layout for each shape, i.e. for shape_top :
You can also do this programatically changing the background.
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:fontFamily="sans-serif-light"
android:text="TextView"
android:textSize="22dp" />
<TextView
android:id="#+id/txtValue1"
android:layout_width="match_parent"
android:layout_height="48dp"
android:textSize="22dp"
android:layout_gravity="right|center"
android:gravity="center|right"
android:layout_marginLeft="20dp"
android:layout_marginRight="35dp"
android:text="Fix"
android:scaleType="fitEnd" />
And define a selector for each shaped-list, i.e. for shape_top:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selected Item -->
<item android:state_selected="true"
android:drawable="#drawable/shape_top" />
<item android:state_activated="true"
android:drawable="#drawable/shape_top" />
<!-- Default Item -->
<item android:state_selected="false"
android:drawable="#android:color/transparent" />
</selector>
Change your CustomAdapter
Finally, define the layout options inside your CustomAdapter:
if(position==0)
{
convertView = mInflater.inflate(R.layout.list_layout_top, null);
}
else
{
convertView = mInflater.inflate(R.layout.list_layout_normal, null);
}
if(position==getCount()-1)
{
convertView = mInflater.inflate(R.layout.list_layout_bottom, null);
}
if(getCount()==1)
{
convertView = mInflater.inflate(R.layout.list_layout_unique, null);
}
And that's done!
to make border u have to make another xml file with property of solid and corners in the drawable folder and calls it in background
I'm using a custom view that I layout on top of the other ones and that just draws the 4 small corners in the same color as the background. This works whatever the view contents are and does not allocate much memory.
public class RoundedCornersView extends View {
private float mRadius;
private int mColor = Color.WHITE;
private Paint mPaint;
private Path mPath;
public RoundedCornersView(Context context) {
super(context);
init();
}
public RoundedCornersView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.RoundedCornersView,
0, 0);
try {
setRadius(a.getDimension(R.styleable.RoundedCornersView_radius, 0));
setColor(a.getColor(R.styleable.RoundedCornersView_cornersColor, Color.WHITE));
} finally {
a.recycle();
}
}
private void init() {
setColor(mColor);
setRadius(mRadius);
}
private void setColor(int color) {
mColor = color;
mPaint = new Paint();
mPaint.setColor(mColor);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
invalidate();
}
private void setRadius(float radius) {
mRadius = radius;
RectF r = new RectF(0, 0, 2 * mRadius, 2 * mRadius);
mPath = new Path();
mPath.moveTo(0,0);
mPath.lineTo(0, mRadius);
mPath.arcTo(r, 180, 90);
mPath.lineTo(0,0);
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
/*Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawRect(0, 0, mRadius, mRadius, paint);*/
int w = getWidth();
int h = getHeight();
canvas.drawPath(mPath, mPaint);
canvas.save();
canvas.translate(w, 0);
canvas.rotate(90);
canvas.drawPath(mPath, mPaint);
canvas.restore();
canvas.save();
canvas.translate(w, h);
canvas.rotate(180);
canvas.drawPath(mPath, mPaint);
canvas.restore();
canvas.translate(0, h);
canvas.rotate(270);
canvas.drawPath(mPath, mPaint);
}
}
There are different ways to achieve it. The latest approach is using CardView for each ListItem component.
Here are some steps.
Create a layout resource file; let's name it "listitem.xml
Copy and paste the under enclosed Listitem.xml layout body into it.
Create RowItem class for each listitem data; later you will instantiate this to assign values for each list item. Check Code below, RowItem.class.
Create a custom ListAdapter; let's name it ListAdapter.class, and inflate this (#1) list item layout for each list item (Check the second code snippet for this one)
Set this adapter (#3) the way you set default adapters inside an activity the listview belongs to. maybe the only difference would be you first have to instantiate RowItem class with values and add RowItem object to your adapter then notify your adapter that the data is changed.
**listitem.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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="wrap_content"
android:orientation="vertical">
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alignmentMode="alignMargins"
android:columnCount="1"
android:columnOrderPreserved="false"
android:rowCount="1">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_margin="6dp"
app:cardCornerRadius="8dp"
app:cardElevation="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/sampleiconimageID"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/titleoflistview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Main Heading"
android:textStyle="bold" />
<TextView
android:id="#+id/samplesubtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sub Heading"
/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</GridLayout>
</LinearLayout>
RowItem.Class
public class RowItem {
private String heading;
private String subHeading;
private int smallImageName;
private String datetime;
private int count;
public void setHeading( String theHeading ) {
this.heading = theHeading;
}
public String getHeading() {
return this.heading;
}
public void setSubHeading( String theSubHeading ) {
this.subHeading = theSubHeading;
}
public String getSubHeading( ) {
return this.subHeading;
}
public void setSmallImageName(int smallName) {
this.smallImageName = smallName;
}
public int getSmallImageName() {
return this.smallImageName;
}
public void setDate(String datetime) {
this.datetime = datetime;
}
public String getDate() {
return this.datetime;
}
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return this.count;
}
}
Sample ListAdapter
public class ListAdapter extends BaseAdapter {
private ArrayList<RowItem> singleRow;
private LayoutInflater thisInflater;
public ListAdapter(Context context, ArrayList<RowItem> aRow){
this.singleRow = aRow;
thisInflater = ( LayoutInflater.from(context) );
}
#Override
public int getCount() {
return singleRow.size(); }
#Override
public Object getItem(int position) {
return singleRow.get( position ); }
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = thisInflater.inflate( R.layout.mylist2, parent, false );
//set listview objects here
//example
TextView titleText = (TextView) view.findViewById(R.id.titleoflistview);
RowItem currentRow = (RowItem) getItem(position);
titleText.setText( currentRow.getHeading() );
}
return view;
// LayoutInflater inflater=.getLayoutInflater();
// View rowView=inflater.inflate(R.layout.mylist, null,true);
//
// titleText.setText(maintitle[position]);
// subtitleText.setText(subtitle[position]);
// return null;
};
}

Categories

Resources