I have a listview in my application, but my problem is that the ListView has an empty row below the last item like this image.
link : http://blog.naver.com/wolfjunghun/220150613193
For example, listview has its list of size of 20, but listview has 21 rows.
How can I get rid of that line(not only using android:footerDividersEnabled="false", but also empty space, too) and empty space...?
Please, somebody help me!
.xml file below
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
>
<ListView
android:id="#+id/list_comment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
android:divider="#drawable/comment_divider"
android:overScrollMode="never"
android:footerDividersEnabled="false"
android:fadingEdgeLength="0dp"
/>
<ImageView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginBottom="50dp"
/>
</LinearLayout>
and call xml in activity :
if(mCellEntity.getComments()!=null&&mCellEntity.getComments().size()>0){
list_comment.setVisibility(View.VISIBLE);
findViewById(R.id.frame_cell).setBackgroundColor(Color.parseColor("#ebedee"));
Collections.sort(mCellEntity.getComments(), new TimeAscCompare());
commentAdapter=new CommentAdapter(this, R.layout.cell_comment_item2, mCellEntity.getComments());
list_comment.setAdapter(commentAdapter);
DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
int margin = (int) ComUtil.convertDpToPixel(40,this);
width = width -margin;
ListViewHelper.getListViewSize(list_comment, width);
}else{
list_comment.setVisibility(View.GONE);
}
getView method in Commentadapter :
public class CommentAdapter extends BaseAdapter {
........... skip ..........
public CommentAdapter(Activity ctx, int layout , ArrayList<CellEntity> timeLineList){
inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.list = timeLineList;
this.ctx = ctx;
this.layout = layout;
this.applicationClass = (ApplicationClass)ctx.getApplicationContext();
SharedPreferences userPref = ctx.getSharedPreferences(CommonConst.PREFS_USER_INFO, Activity.MODE_PRIVATE);
mobileView = userPref.getBoolean(CommonConst.UserInfo.PREFS_MOBILE_VIEW, false);
if (this.mTypeface == null)
this.mTypeface = Typeface.createFromAsset(ctx.getAssets(), "NanumGothicBold.ttf.mp3");
if(ctx instanceof CellMapTimeLineActivity){
isMapView = false;
}else if(ctx instanceof CellMapSkipActivity){
this.layout = R.layout.timeline_skip_item;
isMapView = false;
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.bg_cellmap_line)
.showImageOnFail(R.drawable.bg_cellmap_line)
.resetViewBeforeLoading()
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new FadeInBitmapDisplayer(300))
.build();
icoOptions = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.pic)
.showImageOnFail(R.drawable.pic)
.resetViewBeforeLoading()
.cacheOnDisc()
.build();
typefaceHelveticaBold = Typeface.createFromAsset(ctx.getAssets(), "HelveticaBold.ttf");
}
........... skip ..........
static class ViewHolder {
/////holder setting/////
}
#Override
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
CellEntity row = new CellEntity();
row = list.get(position);
if(view == null){
view = inflater.inflate(layout, parent , false);
holder = new ViewHolder();
holder.img_bottom_line =(ImageView)view.findViewById(R.id.img_bottom_line);
holder.user_name = (TextView)view.findViewById(R.id.user_name);
holder.likeCount = (TextView)view.findViewById(R.id.likeCount);
holder.txt_like = (TextView)view.findViewById(R.id.txt_like);
......... skip ........
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
......... skip ........
return view;
}
......... skip ........
}
It's like that.
I don't understand why that list view call the getView method 21-times even list view has 20 items in the list!
Related
I have a listview that contains a set of a custom view. Inside each custom view is a gridview.
I want to be able to update the background of each cell in the gridview when the user clicks a checkbox in the custom view.
Here is my custom view
<?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:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:id="#+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="32sp" />
<CheckBox
android:id="#+id/lblHeaderCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:focusable="false"
android:layout_centerVertical="true" />
</RelativeLayout>
<ca.package.CustomGridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:gravity="center"
android:numColumns="7"
android:padding="10dp"
android:stretchMode="columnWidth"
clickable="true" />
Here is my layout for each grid cell
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:clickable="true" >
<TextView
android:id="#+id/grid_itemTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
</TextView>
</LinearLayout>
Here is how I fill the list
expListView = (ListView) this.findViewById(R.id.event_list);
prepareListData();
listAdapter = new CustomAdapter(this, listDataHeader,
listDataChild, listChildBoolean);
expListView.setAdapter(listAdapter);
Here is the getView method in my custom adapter for the listView
public View getView(int groupPosition, View convertView, ViewGroup parent) {
final int gp = groupPosition;
String headerTitle = (String) getGroup(groupPosition);
// Boolean bool = _listDataBoolean.get(groupPosition);
Boolean bool = currentCalendarEvents.get(groupPosition).getAlert();
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
String[] data = new String[14];
List<String> times = _currentListDataChild.get(_currentListDataHeader
.get(groupPosition));
data[0] = "Su";
data[1] = "M";
data[2] = "Tu";
data[3] = "W";
data[4] = "Th";
data[5] = "F";
data[6] = "Sa";
data[7] = times.get(6); // sun
data[8] = times.get(0); // mon
data[9] = times.get(1); // tues
data[10] = times.get(2); // wed
data[11] = times.get(3); // thurs
data[12] = times.get(4); // fri
data[13] = times.get(5); // sat
ArrayList<Boolean> boolArray = _listChildBoolean.get(_currentListDataHeader
.get(groupPosition));
final GridView gridView = (GridView) convertView.findViewById(R.id.gridView);
final GridAdapter adapter = new GridAdapter(this._context, data, boolArray);
gridView.setAdapter(adapter);
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
final CheckBox chk2 = (CheckBox) convertView
.findViewById(R.id.lblHeaderCheckbox);
chk2.setChecked(bool);
chk2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (chk2.isChecked()) {
currentCalendarEvents.get(gp).setAlert(true);
currentCalendarEvents.get(gp).setDaysTrue();
// I WANT TO UPDATE THE LIST HERE
Log.i(LOG_TAG, "box checked");
} else {
currentCalendarEvents.get(gp).setAlert(false);
currentCalendarEvents.get(gp).setDaysFalse();
// AND HERE
Log.i(LOG_TAG, "box not checked");
}
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i(LOG_TAG, "gridview clicked");
currentCalendarEvents.get(gp).setBoolDays(adapter.getHashMap());
}
});
return convertView;
}
Here is my GridAdapter
public class GridAdapter extends BaseAdapter {
private Context context;
private String[] items;
private ArrayList<Boolean> boolArray;
private ArrayList<View> views;
LayoutInflater inflater;
public GridAdapter(Context context, String[] items,
ArrayList<Boolean> boolArray) {
this.context = context;
this.items = items;
this.boolArray = boolArray;
this.views = new ArrayList<View>();
inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_cell, null);
final TextView tv = (TextView) convertView
.findViewById(R.id.grid_itemTxt);
tv.setText(items[position]);
if (position < 7) {
convertView.setBackgroundColor(Color.DKGRAY);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
tv.setTextColor(Color.WHITE);
tv.setTypeface(null, Typeface.BOLD);
tv.setLines(2);
} else {
Log.e("blerp", "test : " + items[position]);
if (!items[position].equals("")) {
if (boolArray.get(position % 7)) {
convertView.setBackgroundColor(context.getResources()
.getColor(R.color.LightGreen));
} else {
convertView.setBackgroundColor(Color.LTGRAY);
}
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolArray.get(position % 7)) {
((View) tv.getParent())
.setBackgroundColor(Color.LTGRAY);
boolArray.set(position % 7, false);
} else {
((View) tv.getParent())
.setBackgroundColor(context
.getResources().getColor(
R.color.LightGreen));
boolArray.set(position % 7, true);
}
}
});
} else
convertView.setBackgroundColor(Color.LTGRAY);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
tv.setLines(2);
}
}
return convertView;
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int position) {
return items[position];
}
#Override
public long getItemId(int position) {
return position;
}
public HashMap<String,Boolean> getHashMap() {
HashMap<String, Boolean> hm = new HashMap<String,Boolean>();
hm.put("sun", boolArray.get(0));
hm.put("mon", boolArray.get(1));
hm.put("tues", boolArray.get(2));
hm.put("wed", boolArray.get(3));
hm.put("thurs", boolArray.get(4));
hm.put("fri", boolArray.get(5));
hm.put("sat", boolArray.get(6));
return hm;
}
}
Any help would be greatly appreciated, I can post more of my code if need be.
initiate gridview and checkbox in the adapter class (using find view by id).
then pass
if (checkBox.isChecked) {
gridview.setBackgroundColor(Color.rgb(x,y,z)))}
I am creating a android app in which i have list of channels(items) in a Custom GridView.
I have a favorite icon associated with each channel to add them in favorites list.
On click of this favorite icon the channel gets added to the Favorites List of channels.
When i use a android box remote i am not able to select the ImageView for favorite.
Instead the whole GridItem gets selected.
The single grid item is a LinearLayout which mainly has two ImageViews in it.
View code for a single grid-item of the gridview
<?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:focusable="false"
android:clickable="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/channelLogo"
android:layout_width="75dip"
android:layout_height="75dip"
android:layout_gravity="center"
android:focusable="false"
android:contentDescription="#string/app_name"/>
<TextView
android:id="#+id/channelName"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<TextView
android:id="#+id/channelStatus"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<ImageView
android:id="#+id/addToFavourite"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="false"
android:contentDescription="Add to favourites"
android:src="#drawable/addfavorites"
/>
</LinearLayout>
Code for my grid adapter where i handle the click of the ImageView (for adding a channel to favorite).
public class GridAdapter extends BaseAdapter {
private Context mContext;
private int resourceId;
private ArrayList<Item> itemList = new ArrayList<Item>();
private ArrayList<Category> categoryList = new ArrayList<Category>();
private int size;
private Integer[] mThumbIds;
private ViewGroup gridGroup;
private static final String PREFS_FAVOURITES = "favourites";
public GridAdapter(MainActivity c, int layoutResourceId, ArrayList<Item> data, int gsize) {
mContext = c;
resourceId = layoutResourceId;
itemList = data;
size = gsize;
mThumbIds = new Integer[gsize];
for(int i=0;i<mThumbIds.length;i++) {
mThumbIds[i] = R.drawable.ic_launcher;
}
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int arg0) {
return mThumbIds[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
class ViewHolder {
ImageView imageUrl;
TextView channelNameTxt;
TextView channelStatusTxt;
ImageView imgFavourite;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String contextClass = mContext.getClass().toString();
ViewHolder holder;
gridGroup = parent;
View grid = null;
if(convertView==null){
grid = new View(mContext);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
if (contextClass.contains("MainActivity") || contextClass.contains("FavoriteActivity")) {
grid = inflater.inflate(R.layout.grid_item, parent, false);
}
}else{
grid = (View)convertView;
return grid;
}
if (contextClass.contains("MainActivity")) {
if (position < itemList.size()) {
holder = new ViewHolder();
holder.channelNameTxt = (TextView) grid
.findViewById(R.id.channelName);
String channelName = itemList.get(position).getChannelName().replace("\n", "").replace("\r", "");
holder.channelNameTxt.setText(channelName);
holder.channelStatusTxt = (TextView) grid
.findViewById(R.id.channelStatus);
holder.channelStatusTxt
.setText(itemList.get(position).getStatus());
if(itemList.get(position).getStatus().equalsIgnoreCase("Online")) {
holder.channelStatusTxt.setTextColor(Color.GREEN);
} else if(itemList.get(position).getStatus().equalsIgnoreCase("Offline")) {
holder.channelStatusTxt.setTextColor(Color.RED);
}
holder.imageUrl = null;
try {
holder.imageUrl = (ImageView) grid
.findViewById(R.id.channelLogo);
holder.imageUrl.setTag(itemList.get(position).getImageUrl());
new DownloadImagesTask().execute(holder.imageUrl);
notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex.toString());
}
final Item info = itemList.get(position);
holder.imgFavourite = (ImageView)grid.findViewById(R.id.addToFavourite);
holder.imgFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//GridView gridview1;
if(mContext.getClass().toString().contains("MainActivity")) {
GridView gv = (GridView)gridGroup;
final int position = gv.getPositionForView((View) v.getParent());
Toast.makeText(mContext, "Position is :" + position, Toast.LENGTH_SHORT).show();
SharedPreferences settings = mContext.getSharedPreferences(PREFS_FAVOURITES, 0);
String favourites = settings.getString("favourites", "");
Item clicked_item = itemList.get(position);
String sep1 = "<sep1>";
String sep = "<sep>";
String favourite = clicked_item.getChannelUrl()+sep1+clicked_item.getChannelName()+sep1+clicked_item.getStatus()+sep1+"Favorite"+sep1+clicked_item.getImageUrl()+sep;
favourite = favourite.replace("\n", "").replace("\r", "");
if(!favourites.contains(favourite))
favourites = favourites+favourite;
SharedPreferences.Editor editor = settings.edit();
editor.putString("favourites", favourites);
editor.commit();
}
}
});
grid.setTag(holder);
}
}
return grid;
}
This works fine on a android phone.
I have been searching everywhere for similar solutions but none seem to work for me.
On my first screen I will have a gridview which consists of 1 column and 3 rows vertically. Each row will have an imageview and a partially transparent textview on top of the text view. The imageviews span the screen width fine. My only problem is that the 3 image views do not span the full screen vertically, there is space inbetween rows, although I have tried many methods to fix this. I will post up my xml files and code:
row_layout.xml - this is the gridview items
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/item_image"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:layout_width="fill_parent"
android:layout_height="180dp"
android:src="#drawable/season1">
</ImageView>
<TextView
android:id="#+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/item_image"
android:layout_alignTop="#+id/item_image"
android:layout_alignRight="#+id/item_image"
android:layout_alignBottom="#+id/item_image"
android:gravity="bottom|left"
android:textSize="30sp"
android:textAlignment="center"
android:lines="1"
android:layout_marginTop="145dp"
android:background="#99000000">
</TextView>
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<GridView
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:padding="0dp"
android:gravity="center"
android:numColumns="1"
android:fitsSystemWindows="true"
android:stretchMode="columnWidth" >
</GridView>
My custom adapter:
public class CustomGridViewAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
ArrayList<Item> data = new ArrayList<Item>();
public CustomGridViewAdapter(Context context, int layoutResourceId, ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
row.setMinimumHeight(MainActivity.height1/3);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
Item item = data.get(position);
holder.txtTitle.setText(item.getTitle());
holder.imageItem.setImageBitmap(item.getImage());// my image
return row;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
MainActivity:
public class MainActivity extends ActionBarActivity {
GridView gridView;
ArrayList<Item> gridArray = new ArrayList<Item>();
CustomGridViewAdapter customGridAdapter;
public static int height1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
ActionBar ab = getActionBar();
ab.setDisplayShowTitleEnabled(false);
ab.setDisplayShowHomeEnabled(false);
Resources res = this.getResources();
Bitmap bMap = BitmapFactory.decodeResource(res, R.drawable.actionbar);
BitmapDrawable actionBarBackground = new BitmapDrawable(res, bMap);
ab.setBackgroundDrawable(actionBarBackground);
//set grid view item
Bitmap season1Icon = BitmapFactory.decodeResource(res, R.drawable.season1);
Bitmap season2Icon = BitmapFactory.decodeResource(res, R.drawable.season2);
Bitmap season3Icon = BitmapFactory.decodeResource(res, R.drawable.season3);
gridArray.add(new Item(season1Icon,"Season 1"));
gridArray.add(new Item(season2Icon,"Season 2"));
gridArray.add(new Item(season3Icon,"Season 3"));
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
height1 = metrics.heightPixels;
gridView = (GridView) findViewById(R.id.gridView1);
customGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, gridArray);
gridView.setAdapter(customGridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent a = new Intent(MainActivity.this, House.class);
a.putExtra("Position", position);
startActivity(a);
}
});
}
}
Any help will be greatly appreciated, I've spent hours trying to fix this!
Dynamically set the layout params of your imageview, once you know the height of the screen.
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
//row.setMinimumHeight(MainActivity.height1/3); //don't need this, since wrap content will make the row height match your image view's
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.imageItem = (ImageView) row.findViewById(R.id.item_image);
holder.imageItem.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, MainActivity.height1/3);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
below is my code which works fine for showing listview horizontally. how can I change it to gridvew. What changes should I make to change it to gridview? help me please
public class fifthscreen extends Activity {
int IOConnect = 0;
String _response;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
String name;
String url1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new TheTask().execute();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
try {
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
listview.setAdapter(cla);
}
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return fifthscreen.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(fifthscreen.Category_name.get(position));
// imageLoader.DisplayImage(fifthscreen.Category_image.get(position),
activity, holder.imgThumb);
androidAQuery.id(holder.imgThumb).image(fifthscreen.Category_image.get(position), false,
false);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
<!--- fifithscreen.xml--->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_below="#+id/test_button_text5"
android:orientation="vertical" >
<com.example.examplecode.HorizontalListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="120dp"
android:layout_below="#+id/test_button_text5"
android:background="#ffffff"/>
</LinearLayout>
<!--viewitem2.xml--->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView
android:id="#+id/image2"
android:layout_width="90dp"
android:layout_height="70dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/title2"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:textColor="#000"
android:paddingTop="10dp"
android:gravity="center_horizontal"
/>
</LinearLayout>
No change at all. Just set adapter of GridView as your are setting for ListView.
I'd suggest that you use RecyclerView intead.
You might want to refer to the documentation and learn more about it.
I'm sharing my piece of code in which I'm changing my gridview to listview using RecyclerView
If you're using Android Studio then you might need to add dependencies in gradle build. In my case I added as follows:
dependencies {
.
.
.
compile 'com.android.support:recyclerview-v7:24.0.0'
}
First I'm defining a grid cell which is to be used in grid layout
recycler_cell.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView2"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:background="#FF000000"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView2"
android:layout_below="#+id/imageView2"
android:layout_alig=nParentStart="true"
android:layout_alignEnd="#+id/imageView2"
android:gravity="center"/>
</RelativeLayout>
Now I'm defining a list row which is to be used in list layout
recycler_row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:background="#FF000000"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignBottom="#+id/imageView"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/imageView"
android:gravity="center_vertical"
android:background="#FF333333"
android:textColor="#FFF"
android:padding="10dp"/>
</RelativeLayout>
recycler_view_test.xml
And of course define a layout which would contain RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:layout_centerHorizontal="true"
>
</android.support.v7.widget.RecyclerView>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Layout"
android:id="#+id/btnChange"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="62dp"/>
</RelativeLayout>
I'm sharing my piece of code but I'd strongly recommend that you go through the documentation and tutorials to understand RecyclerView to its full extent.
public class RecyclerViewTest extends AppCompatActivity
{
final int GRID = 0;
final int LIST = 1;
int type;
RecyclerView recyclerView;
RecyclerView.LayoutManager gridLayoutManager, linearLayoutManager;
MyAdapter adapter;
Button btnChange;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view_test);
// Display contents in views
final List<Person> list = new ArrayList<>();
list.add(new Person("Ariq Row 1"));
list.add(new Person("Ariq Row 2"));
list.add(new Person("Ariq Row 3"));
// Finding views by id
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
btnChange = (Button) findViewById(R.id.btnChange);
// Defining Linear Layout Manager
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
// Defining Linear Layout Manager (here, 3 column span count)
gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
//Setting gird view as default view
type = GRID;
adapter = new MyAdapter(list, GRID);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
//Setting click listener
btnChange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (type == LIST)
{
// Change to grid view
adapter = new MyAdapter(list, GRID);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
type = GRID;
}
else
{
// Change to list view
adapter = new MyAdapter(list, LIST);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
type = LIST;
}
}
});
}
}
//Defining Adapter
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
List<Person> list;
int type;
final int GRID = 0;
final int LIST = 1;
MyAdapter(List<Person> list, int type)
{
this.list = list;
this.type = type;
}
// Inflating views if the existing layout items are not being recycled
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
if (viewType == GRID)
{
// Inflate the grid cell as a view item
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cell, parent, false);
}
else
{
// Inflate the list row as a view item
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
}
return new ViewHolder(itemView, viewType);
}
// Add data to your layout items
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
Person person = list.get(position);
holder.textView.setText(person.name);
}
// Number of items
#Override
public int getItemCount()
{
return list.size();
}
// Using the variable "type" to check which layout is to be displayed
#Override
public int getItemViewType(int position)
{
if (type == GRID)
{
return GRID;
}
else
{
return LIST;
}
}
// Defining ViewHolder inner class
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textView;
final int GRID = 0;
final int LIST = 1;
public ViewHolder(View itemView, int type)
{
super(itemView);
if (type == GRID)
{
textView = (TextView) itemView.findViewById(R.id.textView2);
}
else
{
textView = (TextView) itemView.findViewById(R.id.textView);
}
}
}
}
// Data Source Class
class Person
{
String name;
Person(String name)
{
this.name = name;
}
}
If you end up with the issue to auto fit the number of columns in case of grid layout then you might want to check #s-marks's answer in which he extended the GridLayoutManager class and added his own patch of code, and also my fix if you start having weird column width.
In my case, using his solution I made a class as follows:
class GridAutofitLayoutManager extends GridLayoutManager
{
private int mColumnWidth;
private boolean mColumnWidthChanged = true;
public GridAutofitLayoutManager(Context context, int columnWidth)
{
/* Initially set spanCount to 1, will be changed automatically later. */
super(context, 1);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
public GridAutofitLayoutManager(Context context, int columnWidth, int orientation, boolean reverseLayout)
{
/* Initially set spanCount to 1, will be changed automatically later. */
super(context, 1, orientation, reverseLayout);
setColumnWidth(checkedColumnWidth(context, columnWidth));
}
private int checkedColumnWidth(Context context, int columnWidth)
{
if (columnWidth <= 0)
{
/* Set default columnWidth value (48dp here). It is better to move this constant
to static constant on top, but we need context to convert it to dp, so can't really
do so. */
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48,
context.getResources().getDisplayMetrics());
}
else
{
columnWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, columnWidth,
context.getResources().getDisplayMetrics());
}
return columnWidth;
}
public void setColumnWidth(int newColumnWidth)
{
if (newColumnWidth > 0 && newColumnWidth != mColumnWidth)
{
mColumnWidth = newColumnWidth;
mColumnWidthChanged = true;
}
}
#Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state)
{
int width = getWidth();
int height = getHeight();
if (mColumnWidthChanged && mColumnWidth > 0 && width > 0 && height > 0)
{
int totalSpace;
if (getOrientation() == VERTICAL)
{
totalSpace = width - getPaddingRight() - getPaddingLeft();
}
else
{
totalSpace = height - getPaddingTop() - getPaddingBottom();
}
int spanCount = Math.max(1, totalSpace / mColumnWidth);
setSpanCount(spanCount);
mColumnWidthChanged = false;
}
super.onLayoutChildren(recycler, state);
}
}
Then you simply have to change:
gridLayoutManager = new GridLayoutManager(getApplicationContext(), 3);
and use your custom grid layout object, here 100 is the width of columns in dp
gridLayoutManager = new GridAutofitLayoutManager(getApplicationContext(), 100);
You can do something like this:
For the layout of the grid/list use a merge:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ViewStub android:id="#+id/list"
android:inflatedId="#+id/showlayout"
android:layout="#layout/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
<ViewStub android:id="#+id/grid"
android:inflatedId="#+id/showlayout"
android:layout="#layout/grid_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</merge>
then define the layout for the list and the grid (and also for their items), and manage the passage between them inflating the layouts, and then use a method like this to change the current view:
private void changeView() {
//if the current view is the listview, passes to gridview
if(list_visibile) {
listview.setVisibility(View.GONE);
gridview.setVisibility(View.VISIBLE);
list_visibile = false;
setAdapters();
}
else {
gridview.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
list_visibile = true;
setAdapters();
}
}
If you need the complete code, it is available in this article:
http://pillsfromtheweb.blogspot.it/2014/12/android-passare-da-listview-gridview.html
Just take a GridView object instead of Listview like :
GridView gridView;
gridView= (GridView) this.findViewById(R.id.gridView1);
And in you getView method of CategoryListAdapter3 do like :
convertView = inflater.inflate(R.layout.your_grid_item_leyout, null);
And at last in onPostExecute of TheTask do like :
gridView.setAdapter(cla);
That's It.
Use GridView instead of below:
Then replace
listview = (HorizontalListView) this.findViewById(R.id.listview2);
to
GridView gridview;
gridview=(GridView) findViewById(R.id.gridview);
Everything else are fine, just set Adapter using GridView object. And you are done.
I am using the following code.
Adapter.java class
public class Adapter extends ArrayAdapter<String> {
private java.util.List<String> List;
private Context context;
public Adapter(List<String> list, Context ctx) {
super(ctx, R.layout.row_item, list);
this.List = list;
this.context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
NameHolder holder = new NameHolder();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row_item, null);
TextView tv = (TextView)v.findViewById(R.id.textView1);
LinearLayout ll = (LinearLayout) v.findViewById(R.id.myLayout);
holder.topic_name = tv;
holder.myLayout = ll;
v.setTag(holder);
}
else
holder = (NameHolder) v.getTag();
String topic = List.get(position);
holder.topic_name.setText(topic);
ImageView imgUsers = new ImageView(context);
imgUsers.setImageResource(R.drawable.ic_launcher);
holder.myLayout.addView(imgUsers);
return v;
}
private static class NameHolder {
public TextView topic_name;
public LinearLayout myLayout;
}
}
MainActivity.java class :
public class MainActivity extends Activity {
ListView lv;
ArrayList<String> list;
Adapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.listView1);
list = new ArrayList<String>();
for(int i=0; i<10;i++){
list.add("Name"+i);
}
myAdapter = new Adapter(list, MainActivity.this);
lv.setAdapter(myAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"lets see"+list.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main.xml :
<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/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
row_item.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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:orientation="horizontal"
android:id="#+id/myLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Now, the expected output is a single image in every listItem, which tend to go to infinite.
And the onItemClickListener is not working as well.
Also, onItemClickListener works if we don't add HorizontalScrollView.
Writing onClickListener() in Adapter itself helps little as it works unpredictably.
Also, on adding a print statement in getView() and observing in Logcat, I find it difficult to understand the pattern in which getView() is called.
These are the problems I face. I require a working code of the things I wish to apply. Thanks in advance.
// Replace this code
public View getView(int position, View convertView, ViewGroup parent) {
NameHolder holder;
if (convertView == null) {
holder = new NameHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_item, null);
holder.topic_name = (TextView)convertView.findViewById(R.id.textView1);
holder.myLayout = (LinearLayout) convertView.findViewById(R.id.myLayout);
convertView.setTag(holder);
}
else
holder = (NameHolder) convertView.getTag();
String topic = List.get(position);
holder.topic_name.setText(topic);
ImageView imgUsers = new ImageView(context);
imgUsers.setImageResource(R.drawable.ic_launcher);
holder.myLayout.removeAllViews();
holder.myLayout.addView(imgUsers);
convertView.setTag(holder);
return convertView;
}
Looks like you are adding an ImageView every single time here
ImageView imgUsers = new ImageView(context);
imgUsers.setImageResource(R.drawable.ic_launcher);
holder.myLayout.addView(imgUsers);
Why don't you include the ImageView as part of your list item layout?