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.
Related
I am using linkify to make links clickable in the textview. But whenever text length is big, the text flickers on scrolling or sometimes just disappears. The text view is part of header of recyclerview. Posting relevant code from activity class, its xml and adapter.
The Activity:
public class NewDiscussionDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_discussion_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
aQuery = new AQuery(this);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
ab.setTitle("Discussion");
}
Intent activityIntent = getIntent();
discussion_id = Integer.parseInt(activityIntent.getStringExtra("discussion_id"));
discussion_title = activityIntent.getStringExtra("discussion_title");
discussion_text = activityIntent.getStringExtra("discussion_text");
discussion_image_url = activityIntent.getStringExtra("discussion_image_url");
comment_count = Integer.parseInt(activityIntent.getStringExtra("discussion_comment_no"));
community_id = activityIntent.getStringExtra("community_id");
community_name = activityIntent.getStringExtra("community_name");
is_from_notification = activityIntent.getBooleanExtra("is_notification", false);
// initializing header and footer for List view
footer = getLayoutInflater().inflate(R.layout.main_list_footer, null);
header = getLayoutInflater().inflate(R.layout.discussion_detail_header, null);
prepareHeader(header);
recyclerView = (RecyclerView) findViewById(R.id.comment_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mLayoutManager.canScrollVertically();
recyclerView.setLayoutManager(mLayoutManager);
adapter = new CommentAdapter(commentList, this);
/* download page 1*/
adapter.addHeader(header);
recyclerView.setAdapter(adapter);
getCommentList();
/* Scroll Listener which takes care of all triggers to download to load data to adapter based position of the view*/
// code for downloading more pages of comments
}
private void prepareHeader(View header) {
/* preparing the header*/
discussion_image = (ImageView) header.findViewById(R.id.discussion_image_1);
title = (TextView) header.findViewById(R.id.discussion_title);
commentno = (TextView) header.findViewById(R.id.comment_count);
description = (TextView) header.findViewById(R.id.discussion_text_content);
title.setText(discussion_title);
title.setTypeface(AppConstants.getTypeFaceBold(this));
description.setText(discussion_text);
discriptionText = discussion_text + "";
Linkify.addLinks(description, Linkify.WEB_URLS);
description.setTypeface(AppConstants.getTypeFaceNormal(this));
if (comment_count > 2) {
commentno.setText(String.valueOf(comment_count - 1) + " comments");
} else if (comment_count == 2){
commentno.setText(String.valueOf(comment_count - 1) + " comment");
}else {
commentno.setText("Be the first to comment");
}
if (discussion_image_url == null || discussion_image_url.equals("")) {
discussion_image.setVisibility(View.GONE);
//progressbar.setVisibility(View.GONE);
} else {
discussion_image.setVisibility(View.VISIBLE);
final String image_url = discussion_image_url;
if(UtilMethod.isStringNullOrBlank(image_url))
{
//progressbar.setVisibility(View.GONE);
}
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
Picasso.with(this)
.load(image_url)
.placeholder(R.drawable.default_img_big).error(R.drawable.default_img_big)
.transform(new ImageTransformation(width))
.into(discussion_image, new Callback() {
#Override
public void onSuccess() {
// TODO Auto-generated method stub
//progressbar.setVisibility(View.GONE);
}
#Override
public void onError() {
// TODO Auto-generated method stub
//progressbar.setVisibility(View.GONE);
}
});
discussion_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code
}
});
}
}
The Adapter:
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CustomViewHolder> {
ArrayList<CommentListBean> mArrayList;
Context mContext;
String event = "";
public static final int TYPE_HEADER = 111;
public static final int TYPE_FOOTER = 222;
public static final int TYPE_ITEM = 333;
//headers
List<View> headers = new ArrayList<>();
//footers
List<View> footers = new ArrayList<>();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class CustomViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
private View view;
final TextView timestamp_tv;
final TextView chat_username;
final TextView description_tv;
final ImageView author_image_view;
final ImageView comment_image;
public CustomViewHolder(View v) {
super(v);
view = v;
chat_username = (TextView) v.findViewById(R.id.comment_author_chatname);
timestamp_tv = (TextView) v.findViewById(R.id.comment_timestamp);
description_tv = (TextView) v.findViewById(R.id.comment_text);
comment_image = (ImageView) v.findViewById(R.id.comment_image);
author_image_view = (ImageView) v.findViewById(R.id.comment_author_image);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public CommentAdapter(ArrayList<CommentListBean> arrayList, Context context) {
this.mContext = context;
this.mArrayList = arrayList;
}
// Create new views (invoked by the layout manager)
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
if (viewType == TYPE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_list_item, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
} else {
//create a new framelayout, or inflate from a resource
FrameLayout frameLayout = new FrameLayout(parent.getContext());
//make sure it fills the space
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new HeaderFooterViewHolder(frameLayout);
}
}
// Replace the contents of a view (invoked by the layout manager)
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
//check what type of view our position is
if(position < headers.size()){
View v = headers.get(position);
//add our view to a header view and display it
prepareHeaderFooter((HeaderFooterViewHolder) holder, v);
}else if(position >= headers.size() + mArrayList.size()){
View v = footers.get(position-mArrayList.size()-headers.size());
//add oru view to a footer view and display it
prepareHeaderFooter((HeaderFooterViewHolder) holder, v);
}else {
// - code for normal comment view
}
}
#Override
public int getItemViewType(int position) {
//check what type our position is, based on the assumption that the order is headers > items > footers
if(position < headers.size()){
return TYPE_HEADER;
}else if(position >= headers.size() + mArrayList.size()){
return TYPE_FOOTER;
}
return TYPE_ITEM;
}
private void prepareHeaderFooter(HeaderFooterViewHolder vh, View view){
//empty out our FrameLayout and replace with our header/footer
vh.base.removeAllViews();
vh.base.addView(view);
}
//add a header to the adapter
public void addHeader(View header){
if(!headers.contains(header)){
headers.add(header);
//animate
notifyItemInserted(headers.size()-1);
}
}
//remove a header from the adapter
public void removeHeader(View header){
if(headers.contains(header)){
//animate
notifyItemRemoved(headers.indexOf(header));
headers.remove(header);
}
}
//add a footer to the adapter
public void addFooter(View footer){
if (!footers.contains(footer)){
footers.add(footer);
//animate
notifyItemInserted(headers.size()+mArrayList.size()+footers.size()-1);
}
}
//remove a footer from the adapter
public void removeFooter(View footer){
if(footers.contains(footer)) {
//animate
notifyItemRemoved(headers.size()+mArrayList.size()+footers.indexOf(footer));
footers.remove(footer);
}
}
//our header/footer RecyclerView.ViewHolder is just a FrameLayout
public static class HeaderFooterViewHolder extends CustomViewHolder{
FrameLayout base;
public HeaderFooterViewHolder(View itemView) {
super(itemView);
this.base = (FrameLayout) itemView;
}
}
}
XML for the header view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/message_list_image_layout"
android:orientation="horizontal"
android:paddingTop="20dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="Representative image for the discussion"
android:background="#color/background_color"
android:id="#+id/discussion_image_1"
android:layout_marginBottom="#dimen/margin_5"
android:layout_marginTop="#dimen/margin_5"
android:src="#drawable/bg"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:maxHeight="280dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/discussion_title"
android:text="This is heading of the content"
android:layout_marginLeft="#dimen/margin_20"
android:layout_marginRight="#dimen/margin_20"
style="#style/Base.TextAppearance.AppCompat.Display1"
android:alpha="075" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/discussion_text_content"
android:layout_marginTop="#dimen/margin_10"
android:layout_marginLeft="#dimen/margin_20"
android:layout_marginRight="#dimen/margin_20"
android:text="this is the text of content. this is the text of content. this is the text of content. this is the text of content. this is the text of content.this is the text of content. this is the text of content. this is the text of content. this is the text of content. this is the text of content."
style="#style/Base.TextAppearance.AppCompat.Body1"
android:alpha="0.75" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="#dimen/margin_10"
android:layout_marginLeft="#dimen/margin_20"
android:layout_marginRight="#dimen/margin_20"
android:background="#color/dark_background_color"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginTop="#dimen/margin_10"
android:layout_marginBottom="#dimen/margin_10"
android:layout_marginRight="#dimen/margin_20"
android:layout_marginLeft="#dimen/margin_20"
android:gravity="center_vertical|right|end"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/comment_count"
android:text="4 comments" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Screenshots
Normal view
when I scroll a bit
I have a feeling that it has something to do with LinkMovementMethod. Please help.
I divide my screen in two parts, one of the parts contain five buttons and another part contain seven ImageView with images. Now I want that ImageView rotate infinite,means, after last image, again images start to come. My XML is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="true"
tools:context="in.example.splitapp.MainActivity" >
<ScrollView
android:id="#+id/scrollView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout1"
android:orientation="vertical"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_green_dark">
<Button android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:text="DOG"/>
<Button android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button1"
android:text="CAT"/>
<Button android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button2"
android:text="COW"/>
<Button android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button3"
android:text="RAT"/>
<Button android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button4"
android:text="PARROT"/>
</RelativeLayout>
</ScrollView>
<ScrollView
android:id="#+id/scrollView2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout2"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_purple"
>
<ImageView android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/dog"
android:text="DOG"/>
<ImageView android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView1"
android:background="#drawable/cat"
android:text="CAT"/>
<ImageView android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView2"
android:background="#drawable/cow"
android:text="COW"/>
<ImageView android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView3"
android:background="#drawable/rat"
android:text="RAT"/>
<ImageView android:id="#+id/imageView5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView4"
android:background="#drawable/parrot"
android:text="PARROT"/>
<ImageView android:id="#+id/imageView6"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView5"
android:background="#drawable/horse"
android:text="HORSE"/>
<ImageView android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView6"
android:background="#drawable/fish"
android:text="FISH"/>
</RelativeLayout>
</ScrollView>
</LinearLayout>
I want that ImageView side scrolling infinite means these five images repeated always.
This is my MainActivity:
public class MainActivity extends Activity implements OnScrollListener {
List<String> animalNameList = new ArrayList<String>();
ArrayList<Integer> animalImageList = new ArrayList<Integer>();
ImageAdapter imageAdapter;
NameAdapter nameAdapter = null;;
boolean flag = false;
ListView listView;
ListView listView1;
ListView upperListView;
RelativeLayout parentLayout;
LinearLayout childLayout;
int index = 0;
UpdateAdapter updateAdapter = null;
ArrayList<DataSplit> array = new ArrayList<DataSplit>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animalNameList.add("CAT");
animalNameList.add("DOG");
animalNameList.add("COW");
animalNameList.add("RAT");
animalNameList.add("PARROT");
animalNameList.add("HORSE");
animalNameList.add("FISH");
animalImageList.add(R.drawable.horse);
animalImageList.add(R.drawable.parrot);
animalImageList.add(R.drawable.fish);
animalImageList.add(R.drawable.rat);
animalImageList.add(R.drawable.dog);
animalImageList.add(R.drawable.cat);
animalImageList.add(R.drawable.cow);
parentLayout = (RelativeLayout)findViewById(R.id.parentRelative);
childLayout = (LinearLayout)findViewById(R.id.childLinearLayout);
nameAdapter = new NameAdapter(MainActivity.this,
-1, animalNameList);
listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(nameAdapter);
imageAdapter = new ImageAdapter(MainActivity.this, -1, animalImageList);
listView1 = (ListView)findViewById(R.id.listView2);
CircularListAdapter circularAdapter = new CircularListAdapter(imageAdapter);
listView1.setDivider(null);
listView1.setAdapter(circularAdapter);
listView1.setOnScrollListener(this);
upperListView = (ListView)findViewById(R.id.upperListView);
listView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if(flag)
{
}
}
});
}
class NameAdapter extends BaseAdapter {
private List<String> animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
List<String> animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
button.setId(position);
button.setText(animalName.get(position));
}
return convertView;
}
public int getCount()
{
int size = animalName.size();
return size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
class ImageAdapter extends ArrayAdapter<Integer> {
private ArrayList<Integer> animalImage;
private Activity context;
public ImageAdapter(Activity context, int textViewResourceId,
ArrayList<Integer> animalImage) {
super(context, textViewResourceId);
this.animalImage = animalImage;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
//view.setBackgroundResource(animalImage[position]);
view.setBackgroundResource(animalImage.get(position));
return view;
}
public int getCount()
{
int size = animalImage.size();
return size;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int childInt = view.getChildAt(0).getId();
//String img1Text = this.getResources().getResourceEntryName(animalImage[childInt]);
String img1Text = this.getResources().getResourceEntryName(animalImageList.get(childInt));
//String buttonText = animalName[index];
String buttonText = animalNameList.get(index);
if(img1Text.equalsIgnoreCase(buttonText))
{
final String name = animalNameList.get(index);
int image = animalImageList.get(childInt);
DataSplit data = new DataSplit();
data.setAnimalName(name);
data.setAnimalImage(image);
array.add(data);
index++;
flag = true;
if(array.size() == 1)
{
updateAdapter = new UpdateAdapter(MainActivity.this,-1,array);
upperListView.setAdapter(updateAdapter);
upperListView.setVisibility(View.VISIBLE);
}
else
{
updateAdapter.notifyDataSetChanged();
}
listView.post(new Runnable() {
#Override
public void run() {
animalNameList.remove(name);
nameAdapter.notifyDataSetChanged();
}
});
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
class UpdateAdapter extends ArrayAdapter<Integer> {
ArrayList<DataSplit> dataSplit;
private Activity context;
public UpdateAdapter(Activity context, int textViewResourceId,
ArrayList<DataSplit> dataSplit) {
super(context, textViewResourceId);
this.dataSplit = dataSplit;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.addeddata, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
ImageView imageView=(ImageView)convertView.findViewById(R.id.imageView);
String animalName = dataSplit.get(position).getAnimalName();
int imageName = dataSplit.get(position).getAnimalImage();
button.setText(dataSplit.get(position).getAnimalName());
imageView.setBackgroundResource(dataSplit.get(position).getAnimalImage());
}
return convertView;
}
public int getCount()
{
int size = dataSplit.size();
return size;
}
}
}
I created activity_main.xml which contains a parent RelativeLayout and under this a ListView named upperListView and initially set visibility gone. Below this I created a LinearLayout and for this I created two ListView for Name DataSet and Image DataSet. When data matches I create a UpdateAdapter in which I use addeddata.xml, in which a button and ImageView created and when it is a successful match then hidden list view visibility becomes Visible and this "addeddata.xml" loaded in listview. This I perform. It will work perfectly.But when first matches,i.e, CAT name match with the Cat image, data is not deleted from both of listview and CAT name again shown in below the new ListView.
How to manage to complete matches if the application crashes.
This has been discussed in the past, with using circular Listviews:
How to create a closed (circular) ListView?
Closed or circular Horizontal ListView Android
I just want when I scroll ImageView part then if Dog image matches with the right end side Dog name then image stick with the Dog Name Button and rest of the images remain scrolling.
For this here is what you could try:
after scrolling items in list1 and list2, iterate over each item in the shortest listview and check if item1(position) [tag] = item2(position) [tag] (so, if you have a match)
if true:
redraw screen like this: add a new listview at the bottom of the screen (below both listviews). This listview with contain both item1 and item2 (so it's litviewitem xml will be a linear layout with other two linear layouts, one containing the matched pet name and the other the matched pet picture)
remove item1(position) and item2(position) from listview1, listview2 (which means you have to remove, for example, dog name from listview pet names datasource, and dog image from listview pet pictures datasource and reset adapters to listviews)
this way you will continue to be able to scroll and match items from listview1 and listview2 - without the already matching items-, and also have a bottom listview with all the matching elements that cannot be matched any more
Hope this helps!
After spend couple of days I found the perfect solution for my question. I dynamically created the ImageView and also the ListView. Image data are populating in the ListView. After matching the text with right Image, I take that ImageView from the List and set in dynamically created ImageView. Following is my code.
public class MainActivity extends Activity implements OnScrollChangedListener, OnScrollListener{
int index = 0;
ImageView imageView1;
List<Integer> spectrum = new ArrayList<Integer>();
String[] animalName;
ImageView[] imageArray;
Button[] buttonArray;
ListView listView;
SpectrumAdapter spectrumAdapter;
ListView animalImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
animalName = new String[]{"CAT","DOG","COW","RAT","PARROT","HORSE","FISH"};
imageArray = new ImageView[animalName.length];
buttonArray = new Button[animalName.length];
LinearLayout inner1 = (LinearLayout)findViewById(R.id.innerLayout1);
LinearLayout inner2 = (LinearLayout)findViewById(R.id.innerLayout2);
ListView animalList = (ListView)findViewById(R.id.animalList);
NameAdapter nameAdapter = new NameAdapter(MainActivity.this,
-1, animalName);
animalList.setAdapter(nameAdapter);
for(int i=0;i<animalName.length;i++)
{
ImageView imageView = new ImageView(this);
imageView.setId(i);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,150);
imageView.setTag(i);
imageView.setLayoutParams(params1);
imageView.setVisibility(View.GONE);
imageArray[i] = imageView;
inner1.addView(imageView);
}
ListView listView = new ListView(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
listView.setLayoutParams(param);
inner2.addView(listView);
spectrum.add(R.drawable.horse);
spectrum.add(R.drawable.rat);
spectrum.add(R.drawable.cow);
spectrum.add(R.drawable.dog);
spectrum.add(R.drawable.fish);
spectrum.add(R.drawable.parrot);
spectrum.add(R.drawable.cat);
spectrumAdapter = new SpectrumAdapter(MainActivity.this,
-1, spectrum);
CircularListAdapter circularAdapter = new CircularListAdapter(spectrumAdapter);
listView.setAdapter(circularAdapter);
listView.setOnScrollListener(this);
}
class NameAdapter extends BaseAdapter {
private String[] animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
String[] animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
}
Button button=(Button)convertView.findViewById(R.id.button);
button.setText(animalName[position]);
return convertView;
}
public int getCount()
{
int size = animalName.length;
return size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
class SpectrumAdapter extends ArrayAdapter<Integer> {
private List<Integer> spectrum;
public SpectrumAdapter(Context context, int textViewResourceId,
List<Integer> spectrum) {
super(context, textViewResourceId, spectrum);
this.spectrum = spectrum;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
view.setBackgroundResource(spectrum.get(position));
return view;
}
public int getCount()
{
int size = spectrum.size();
return size;
}
}
#Override
public void onScrollChanged() {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
int childInt = view.getChildAt(0).getId();
String img1Text = this.getResources().getResourceEntryName(spectrum.get(childInt));
String bb = animalName[index];
if(bb.equalsIgnoreCase(img1Text))
{
ImageView img = imageArray[index];
img.setBackgroundResource(spectrum.get(childInt));
img.setVisibility(View.VISIBLE);
index++;
}
else
{
}
}
}
This is the perfect solution for the question. Thanks all for the suggestion.
How do I create a neverending listview of list items with checkboxes that can be removed with a delete item button? The answer is below.
In order to create a neverending listview the first thing you need to have is a set of two runnables. These threads will update the array of data in your adapter.
final int itemsPerPage = 100;
ArrayList<HashMap<String,String>> listItems = new ArrayList<HashMap<String,String>>();
boolean loadingMore = false;
int item = 0;
//Since we cant update our UI from a thread this Runnable takes care of that!
public Runnable returnRes = new Runnable() {
#Override
public void run() {
//Loop thru the new items and add them to the adapter
if(groceries.getGroceries().size() > 0){
for(int i=0;i < listItems.size();i++) {
HashMap<String,String> grocery = listItems.get(i);
adapter.add(grocery);
}
//Update the Application title
setTitle("Grocery List with " + String.valueOf(groceries.getGroceries().size()) + " items");
//Tell to the adapter that changes have been made, this will cause the list to refresh
adapter.notifyDataSetChanged();
//Done loading more.
loadingMore = false;
}
}
};
//Runnable to load the items
public Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
listItems = new ArrayList<HashMap<String,String>>();
//Get 8 new listitems
for (int i = 0; i < itemsPerPage; i++) {
if (i < groceries.getGroceries().size()) {
listItems.add(groceries.getGroceries().get(i));
item++;
}
}
//Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
Then your onCreate() method should look something like this with an array passed to your adapter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_grocery_list);
//add the footer before adding the adapter, else the footer will not load!
View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.activity_footer_view, null, false);
this.getListView().addFooterView(footerView);
adapter = new ListViewAdapter(this,groceries);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//Here is where the magic happens
this.getListView().setOnScrollListener(new OnScrollListener(){
//useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
//dumdumdum
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//what is the bottom iten that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && !loadingMore && item < groceries.getGroceries().size()){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
}
You will also need a delete method to remove the items with checkboxes and a checkOff method as well. They look like this:
ArrayList<Integer> checkedBoxes = new ArrayList<Integer>();
ArrayList<HashMap<String,String>> checkedItems = new ArrayList<HashMap<String,String>>();
public void deleteItem(View view) {
if (checkedBoxes.size() > 1 || checkedBoxes.size() == 0) {
Toast.makeText(getApplicationContext(), "You can only delete one item at a time. Sorry :(", Toast.LENGTH_LONG).show();
return;
} else {
checkedItems.add(groceries.getGroceries().get(checkedBoxes.get(0)));
groceries.getGroceries().removeAll(checkedItems);
checkedBoxes.clear();
try {
groceries.serialize();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(),CreateGroceryList.class);
startActivity(intent);
}
}
public void checkOff(View view) {
CheckBox box = (CheckBox)view;
DataModel d = (DataModel)box.getTag();
if(!checkedBoxes.contains(d.index)) {
checkedBoxes.add(d.index);
} else {
checkedBoxes.remove((Integer)d.index);
}
}
In order to communicate with the adapter it is helpful to have a DataModel class that will model our information. My DataModel has an index variable to keep track of the selected item.
public class DataModel {
int index;
HashMap<String,String> data;
boolean selected;
public DataModel(int i) {
index = i;
data = new HashMap<String,String>();
selected = false;
}
public HashMap<String, String> getData() {
return data;
}
public void setData(HashMap<String, String> data) {
this.data = data;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
Finally, here is the code for the BaseAdapter:
public class ListViewAdapter extends BaseAdapter {//To create an adapter we have to extend BaseAdapter instead of Activity, or whatever.
private ListActivity activity;
private View vi;
private ArrayList<DataModel> data;
private static LayoutInflater inflater=null;
public ListViewAdapter(ListActivity a, GroceryList g) {
activity = a;
data = new ArrayList<DataModel>();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
groceries = g;
}
public void add(HashMap<String,String> a){
DataModel d = new DataModel(data.size());
d.setData(a);
d.setSelected(false);
data.add(d);
}
public ArrayList<DataModel> getData() {
return data;
}
public int getCount() { //get the number of elements in the listview
return data.size();
}
public Object getItem(int position) { //this method returns on Object by position
return position;
}
public long getItemId(int position) { //get item id by position
return position;
}
public View getView() {
return vi;
}
public View getView(int position, View convertView, ViewGroup parent) { //getView method is the method which populates the listview with our personalized rows
vi=convertView;
final ViewHolder holder = new ViewHolder();
if(convertView==null) {
vi = inflater.inflate(R.layout.custom_row_view, null);
//every item in listview uses xml "listview_row"'s design
holder.name = (CheckBox)vi.findViewById(R.id.name);
holder.price = (TextView)vi.findViewById(R.id.price); // You can enter anything you want, buttons, radiobuttons, images, etc.
holder.quantity = (TextView)vi.findViewById(R.id.quantity);
holder.name
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
DataModel element = (DataModel) holder.name
.getTag();
element.setSelected(buttonView.isChecked());
}
});
vi.setTag(holder);
holder.name.setTag(data.get(position));
ViewHolder vholder = (ViewHolder) vi.getTag();
vholder.name.setChecked(data.get(position).isSelected());
HashMap<String, String> hash = new HashMap<String, String>(); //We need a HashMap to store our data for any item
hash = data.get(position).getData();
vholder.name.setText(hash.get("brand") + " " + hash.get("name")); //We personalize our row's items.
vholder.price.setText("$" + hash.get("price"));
vholder.quantity.setText("Quantity: " + hash.get("quantity"));
} else {
vi = convertView;
((ViewHolder) vi.getTag()).name.setTag(data.get(position));
}
if (holder.name == null) {
ViewHolder vholder = (ViewHolder) vi.getTag();
vholder.name.setChecked(data.get(position).isSelected());
HashMap<String, String> hash = new HashMap<String, String>(); //We need a HashMap to store our data for any item
hash = data.get(position).getData();
vholder.name.setText(hash.get("brand") + " " + hash.get("name")); //We personalize our row's items.
vholder.price.setText("$" + hash.get("price"));
vholder.quantity.setText("Quantity: " + hash.get("quantity"));
}
return vi;
}
}
class ViewHolder {
CheckBox name;
TextView price;
TextView quantity;
public CheckBox getName() {
return name;
}
public void setName(CheckBox name) {
this.name = name;
}
public TextView getPrice() {
return price;
}
public void setPrice(TextView price) {
this.price = price;
}
public TextView getQuantity() {
return quantity;
}
public void setQuantity(TextView quantity) {
this.quantity = quantity;
}
}
You also need a few xml files in your layout folder this is what they will look like:
You need a footerview that will tell your list when to load new items:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:padding="3dp"
android:layout_height="fill_parent">
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="5dp"
android:text="Add more grocery items..."/>
A custom row view that is populated by your BaseAdapter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox"
android:focusable="false"
android:textSize="25dip"
android:onClick="checkOff"
/>
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dip"
android:text="Lastname"
android:textSize="15dip" />
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dip"
android:text="Lastname"
android:textSize="15dip" />
</LinearLayout>
And a parent view, mine is called create_grocery_list because I'm writing a grocery list editor: This one must contain a ListView with the proper id.
<?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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="400dp" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
</LinearLayout>
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="72dp" >
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="105dp"
android:layout_y="0dp"
android:onClick="deleteItem"
android:text="#string/deleteItem" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="8dp"
android:layout_y="0dp"
android:onClick="goToAddItemScreen"
android:text="#string/addItem" />
<Button
android:id="#+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="221dp"
android:layout_y="0dp"
android:onClick="scanner"
android:text="#string/scanCode" />
</AbsoluteLayout>
</LinearLayout>
And that's about it... hope this helps anyone. It's the most complete tutorial you'll find.
I learned all this from this tutorial: http://www.vogella.com/articles/AndroidListView/article.html#androidlists_overview then added the two runnables to make a neverending grocery list :) have fun programming...
I have a custom listView with three textViews. The data comes from a class with three ArrayLists, two of which are strings and the last one is an Integer. I have no problems populating and adding items to the list as I saw that when I displayed the ArrayList values on logCat via log.d, all three ArrayLists had their respectful items.
It seems to me that there is something wrong with the way I display data.
Here are the files:
list_row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/variant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="variant" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="quantity" />
<TextView
android:id="#+id/unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="221dp"
android:layout_toLeftOf="#+id/quantity"
android:text="unit" />
</RelativeLayout>
Here is the part in my activity_order_form.xml that has the listView element.
<RelativeLayout
android:id="#+id/relativeLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/relativeLayout2"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewVariantB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="94dp"
android:text="Variant"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textViewUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="123dp"
android:text="Unit"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listViewProductOrder"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textViewVariantB" >
</ListView>
</RelativeLayout>
Here is the class where the ArrayList are stored.
public class CurrentOrderClass {
private String productName;
//ArrayLists
private ArrayList<String> variantArray = new ArrayList<String>();
private ArrayList<String> unitArray = new ArrayList<String>();
private ArrayList<Integer> quantityArray = new ArrayList<Integer>();
//TODO ArrayList functions
public ArrayList<String> getUnitArray() {
return unitArray;
}
public void setUnitArray(ArrayList<String> unitArray) {
this.unitArray = unitArray;
}
public void addToUnitArray(String unit){
this.unitArray.add(unit);
}
public ArrayList<Integer> getQuantityArray() {
return quantityArray;
}
public void setQuantityArray(ArrayList<Integer> quantityArray) {
this.quantityArray = quantityArray;
}
public void addToQuantityArray(int quantity){
this.quantityArray.add(quantity);
}
public ArrayList<String> getVariantArray() {
return variantArray;
}
public void setVariantArray(ArrayList<String> variantArray) {
this.variantArray = variantArray;
}
public void addToVariantArray(String variantArray){
this.variantArray.add(variantArray);
}
}
Here is the CustomListAdapter.java file
public class CustomListAdapter extends BaseAdapter {
private ArrayList<CurrentOrderClass> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<CurrentOrderClass> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.variantView = (TextView) convertView.findViewById(R.id.variant);
holder.unitView = (TextView) convertView.findViewById(R.id.unit);
holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString());
holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString());
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
return convertView;
}
static class ViewHolder {
TextView variantView;
TextView unitView;
TextView quantityView;
}
public void setListData(ArrayList<CurrentOrderClass> data){
listData = data;
}
}
This is part of my OrderForm.java activity, this shows the onCreate and the method that populates the listView.
public class OrderForm extends Activity {
public TextView tv;
private int variantPosition;
CustomListAdapter customListAdapter;
CurrentOrderClass currentOrder = new CurrentOrderClass();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
tv = (TextView)findViewById(R.id.textViewProduct);
//set variants here
popolateItem();
//set current order listview here
ArrayList image_details = getListData();
final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder);
customListAdapter = new CustomListAdapter(this, image_details);
lv1.setAdapter(customListAdapter);
}
private ArrayList getListData() {
ArrayList results = new ArrayList();
if(currentOrder.getQuantityArray().size() > 10){
loopUntil = currentOrder.getQuantityArray().size();
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray();
currentOrder.getUnitArray();
currentOrder.getVariantArray();
results.add(currentOrder);
}
}
else{
loopUntil = 10;
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray().add(i);
currentOrder.getUnitArray().add("Sample text here." + i);
currentOrder.getVariantArray().add("Another sample text here" + i);
results.add(currentOrder);
}
}
return results;
}
}
When I execute a Log.d statement to display the contents of my ArrayLists, it shows that my quantityArray has elements [0, 1, 2, 3, 4, 5, 6, 7, 9].
I know I can just convert quantityArray to an ArrayList from an ArayList, but I don't want to do that.
I think there's something wrong with my CustomListAdapter.
Any thoughts?
There is no where that you actually set the view, as in, it doesn't do anything, if convertView is null, you can't call any methods of it, convertView, if its is not null, will be ViewHolder in your context, what you need to do is have an object which is extending some type of view, instantiate it, give it methods to set the values, things like that.
For example here is what I use in an adapter that displays simple messages:
public class MessageView extends RelativeLayout {
private TextView mBody;
private String mBodyString = "";
private boolean mDrawn = false;
private boolean mLocal = false;
public MessageView(Context context) {
super(context);
this.drawView();
}
public MessageView(Context context, String body) {
super(context);
mBodyString = body;
this.drawView();
}
public MessageView(Context context, String body, boolean local) {
super(context);
mBodyString = body;
mLocal = local;
this.drawView();
}
private void drawView() {
if (mDrawn)
return;
mDrawn = true;
this.removeAllViews();
LayoutInflater li = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if(mLocal){
this.addView(li.inflate(R.layout.list_item_message_device, this, false),
params);
}else{
this.addView(li.inflate(R.layout.list_item_message_remote, this, false),
params);
}
mBody = (TextView) this.findViewById(R.id.tMessage);
mBody.setText(mBodyString);
}
public void setLocal(){
this.setLocal(true);
}
public void setLocal(boolean local){
mLocal = local;
mDrawn = false;
this.drawView();
}
public void setMessage(String body){
mBodyString = body;
mBody.setText(mBodyString);
}
}
I got it.
I changed
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
to
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityArray().get(position)));
I'm using gridview inside a Listview, but I have a focusable problem.
I have set the width of the gridview, but I fill some items of gridview, on the left space of gridview (which is blank) means items not fill of gridview in listview. If I click on it, it does not perform a listitem click
As given in the image, I want to perform a listview item click if it is clicked anywhere in the list item. I want to get a listitem click.
But when I click on ListView item, that is, GridView then the ListItem click is not working...
public class History extends Activity {
String name, id, description, count, total;
ArrayList<String> TAG_ID = new ArrayList<String>();
ArrayList<String> TAG_COFFEESHOP_NAME = new ArrayList<String>();
ArrayList<String> TAG_COUNT = new ArrayList<String>();
ArrayList<String> TAG_TOTAL = new ArrayList<String>();
Context context;
JSONArray CoffeeUser = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
ListView listView = (ListView) findViewById(R.id.listnew);
listView.setAdapter(new MyCustomAdapter());
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
{
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)paramAnonymousView.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
}
class MyCustomAdapter extends BaseAdapter {
Context ctx;
public MyCustomAdapter() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
SharedPreferences prfs = getSharedPreferences("GUID_FILE_NAME", Context.MODE_PRIVATE);
JSONObject json = jParser.methodhistory("http://api.com");
try {
// Getting Array of Employee
CoffeeUser = json.getJSONArray("CoffeeUser");
// Looping of List
for (int i = 0; i < CoffeeUser.length(); i++) {
JSONObject c = CoffeeUser.getJSONObject(i);
// Storing each json item in variable
id = c.getString("CS_Id");
name = c.getString("ShopName");
count = c.getString("totalstamps");
total = c.getString("threshholdcount");
// Adding all get values into array
if (name != "null") {
TAG_COFFEESHOP_NAME.add(name);
TAG_ID.add(id);
TAG_TOTAL.add(total);
TAG_COUNT.add(count);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return TAG_COFFEESHOP_NAME.size();
}
#Override
public Object getItem(int paramInt) {
return TAG_COFFEESHOP_NAME.get(paramInt);
}
#Override
public long getItemId(int paramInt) {
return paramInt;
}
public class MyCustomHolder {
public GridView localGrid;
public TextView CoffeeShopName,coffeeshopsdescription,coffeeshopid;
}
#Override
public View getView(int paramInt, View paramView,ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) History.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.historylist, null);
holder = new MyCustomHolder();
holder.CoffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
holder.localGrid = (GridView) localView.findViewById(R.id.gridViewdistorylist);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.CoffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
holder.localGrid.setAdapter(new GridAdapterA(History.this, TAG_TOTAL.get(paramInt), TAG_COUNT.get(paramInt)));
holder.localGrid.setFocusable(false);
holder.localGrid.setFocusableInTouchMode(false);
holder.CoffeeShopName.setFocusable(false);
holder.CoffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
}
public class GridAdapterA extends BaseAdapter {
private Context context;
String total,count;
public GridAdapterA(Context context) {
this.context = context;
}
public GridAdapterA(Context context, String total, String count) {
// TODO Auto-generated constructor stub
this.context = context;
this.total = total;
this.count = count;
}
public boolean areAllItemsEnabled()
{
return false;
}
public boolean isEnabled(int position)
{
return false;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.customgrid_row, null);
gridView.setFocusable(false);
ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_item_image);
imageView.setFocusable(false);
int i = 0;
if(count!="null")
i = Integer.parseInt(count);
if (position<i ) {
//imageView.setImageResource(R.drawable.ii);
// textView.setText(gridlist[position]);
}
else {
imageView.setImageResource(R.drawable.changedcup);
// textView.setText("");
}
}
else {
gridView = (View) convertView;
}
/*gridView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent); }
});*/
return gridView;
}
#Override
public int getCount() {
int j=0;
if(total!="null"){
j = Integer.parseInt(total);
}
return j;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
}
historylist
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:background="#drawable/image_bg"
android:padding="3dip" >
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/rcup" />
</LinearLayout>
<!-- hlcoffeeshopname Of Song -->
<TextView
android:id="#+id/hlcoffeeshopname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Rihanna Love the way lie"
android:textColor="#040404"
android:textSize="20dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/hlcoffeeshopid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridViewdistorylist"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/hlcoffeeshopname"
android:layout_toRightOf="#+id/thumbnail"
android:columnWidth="20dp"
android:background="#null"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
android:numColumns="10"
android:stretchMode="none" >
</GridView>
</RelativeLayout>
New GetView
#Override
public View getView(int paramInt,
View paramView,
ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) CopyOfHistory.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.copyhistorylist, null);
holder = new MyCustomHolder();
holder.coffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.coffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
int looplimit = Integer.parseInt(TAG_TOTAL.get(paramInt));
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
} else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
}
holder.coffeeShopName.setFocusable(false);
holder.coffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView) v
.findViewById(R.id.hlcoffeeshopid)).getText());
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
You might have solved it, but I have another solution that may help someone.
Use android:descendantFocusability="beforeDescendants" in the root layout of your list_cell XML.
Order to have lists within other lists. You must generate a custom view. If you want one the simple, consisting of a Java class and an XML file, then in the code you only have to instantiate it and add it to a linear layout.
Here I leave a small example.
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<TextView
android:id="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical"
android:text="-"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtListadoZonasNombreZona"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_toRightOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:singleLine="true"
android:text="TextView"
android:textColor="#000000" />
</RelativeLayout>
Java code
public class CVTexto extends RelativeLayout {
public TextView txtTexto;
public int idCv;
public CVTexto(Context context) {
super(context);
// TODO Auto-generated constructor stub
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs) {
super(context, attrs);
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs, int defStyle) {
super( context, attrs, defStyle );
IniciarCuadro();
}
private void IniciarCuadro()
{
//Utilizamos el layout 'control_login' como interfaz del control
String infService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li =
(LayoutInflater)getContext().getSystemService(infService);
li.inflate(R.layout.ll_adapter_listado_zonas_asignadas_usuario, this, true);
AsignarElemetos();
//Obtenemoslas referencias a los distintos control
//Asociamos los eventos necesarios
// asignarEventos();
}
private void AsignarElemetos(){
txtTexto = (TextView)findViewById(R.id.txtListadoZonasNombreZona);
}
}
Add to linearlayout:
cvTextp objCV = new cvTexto(context);
LinearLayout.addView(objCv);
And delete views:
LinearLayout.removeallViews;
I got this answer by changing the grid layout to LinearLayout. I added items dynamically into linearLayout, and then my problem was solved.
I have done research on it and I get to know that inside a scrollable widget which uses an adapter you should not use any other widget which is scrollable which also uses an adapter such as gridview inside listview because of touch events complexity.
So I think you should move to another approach for this. In your case, you can add a linear layout and can add cup images dynamically into that layout by setting parameters. I hope this helped you.
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}