I am creating food shop app in which click on menu button on home page it should redirect to grid view ,
i have created image grid layout xml and image grid class , but not able to map it with button on home page
this is my main activity
public class TimmyRestaurantActivity extends Activity {
Button go_to_menu,go_to_order_list,findstore,info;
//Button custinfo;
String user_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myintent = getIntent();
Bundle extras = myintent.getExtras();
user_name = extras.getString("cust_name");
Toast.makeText(TimmyRestaurantActivity.this, "Welcome " + user_name ,Toast.LENGTH_LONG ).show();
// initialise form widget
go_to_menu=(Button)findViewById(R.id.Go_To_Menu);
go_to_menu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i=new Intent(TimmyRestaurantActivity.this,
ImageAdapter.class);
startActivity(i);
}
}
this is my gridlayout
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
this is adaptor class for my grid
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.img15, R.drawable.img15,
R.drawable.img15, R.drawable.img15
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
and on menuscreen.java i am trying call my gridadapater
public class MenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
on click button , this error comes
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.restaurant/com.restaurant.MenuScreen}:
java.lang.RuntimeException: Your content must have a ExpandableListView whose id attribute is 'android.R.id.list'
How can i properly redirect from home page button to grid view page , please suggest
Add a placeholder in your main laout(R.layout.main)
<FrameLayout
android:layout_height="match_parent"
android:id="#+id/place_men"
android:layout_width="match_parent">
</FrameLayout>
and chnage the code like
go_to_menu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//starting new fragment on button click
MenuScreen menuScreen =new MenuScreen();
getSupportFragmentManager().beginTransaction().replace(R.id.place_men, menuScreen).commit();
}
});
Also MenuScreen extends android.support.v4.app.Fragment
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0">
<GridView
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
</RelativeLayout>
grid_item_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#drawable/grid_color_selector"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp" />
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="12sp" />
</LinearLayout>
GridViewAdapter.class
public class GridViewAdapter extends ArrayAdapter {
private Context context;
private int layoutResourceId;
private ArrayList data = new ArrayList();
public GridViewAdapter(Context context, int layoutResourceId, ArrayList 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;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
ImageItem.class pojo class
public class ImageItem {
private Bitmap image;
private String title;
public ImageItem(Bitmap image, String title) {
super();
this.image = image;
this.title = title;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
MainActivity.class
public class MainActivity extends ActionBarActivity {
private GridView gridView;
private GridViewAdapter gridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, getData());
gridView.setAdapter(gridAdapter);
}
// Prepare some dummy data for gridview
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
Please follow this code implementation for Gridview
And in your button click event
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(YourActivity.this, MainActivity.class);
startActivity(intent);
}
});
Follow this link for working example
Image GridView
Related
I want to set up a Activity with a GridView that has custom views which are added using an ArrayAdapter, but on the emulator the gridview doesn't display anything, here's my code
The Activity with Gridview
public class ContactActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_activity);
GridView gv = (GridView) findViewById(R.id.gv);
Contact c1 = new Contact(1,"a","ab","01","a#outlook.fr");
Contact c2 = new Contact(2,"b","cd","02","b#outlook.fr");
Contact c3 = new Contact(3,"c","ef","03","c#outlook.fr");
Contact c4 = new Contact(4,"d","gh","04","d#outlook.fr");
Contact c5 = new Contact(5,"e","ij","05","e#outlook.fr");
List<Contact> listc = new ArrayList<>();
listc.add(c1);
listc.add(c2);
listc.add(c3);
listc.add(c4);
listc.add(c5);
ContactAdapter ca = new ContactAdapter(this, R.layout.item, listc);
gv.setAdapter(ca);
Intent intent = getIntent();
final Intent i = new Intent(this, AjouterContactActivity.class);
FloatingActionButton a = (FloatingActionButton) findViewById(R.id.fab);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(i);
}
});
}}
The class extending ArrayAdapter
public class ContactAdapter extends ArrayAdapter {
List<Contact> items;
int viewResourecId;
public ContactAdapter(Context context, int viewResourecId, List<Contact> items) {
super(context,viewResourecId);
this.viewResourecId=viewResourecId;
this.items=items;
}
#Override
public int getCount() {
return 0;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView= convertView;
if(convertView==null){
LayoutInflater inflater1 = (LayoutInflater) ((ContactActivity)getContext()).getLayoutInflater();
itemView = inflater1.inflate(viewResourecId,parent,false);
}
TextView tv1 = (TextView)itemView.findViewById(R.id.name);
TextView tv2 = (TextView)itemView.findViewById(R.id.cap);
tv2.setText(items.get(position).getNom().charAt(0));
tv1.setText(items.get(position).getNom()+" "+items.get(position).getPrenom());
return itemView;
}}
the custom item layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="192dp"
android:layout_height="50dp"
android:id="#+id/cap"
android:gravity="center|top"
/>
<TextView
android:layout_width="192dp"
android:layout_height="10dp"
android:id="#+id/name"
android:layout_below="#+id/cap"
android:gravity="center|bottom"
/>
</RelativeLayout>
Here's an image of the acticivity
You need to give some code to getCount and getItemId methods. For example:
#Override
public int getCount() {
return items.size();
}
#Override
public long getItemId(int position) {
return position;
}
I have a custom Listview where it contains image & text and implemented the OnItemClickListener for list which should work only for image not for text. OnItemClick is working fine for image but there is a Fatal Exception when i click on text. Additionally image will be visible in list if it exists else it will be hide.
Tried with android:focusable="false", android:clickable="false" but still i am getting the below exception
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable.getBitmap()' on a null object reference
OnItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ImageView imageView1 = (ImageView) view.findViewById(R.id.imageList);
final GlideBitmapDrawable bitmapDrawable = (GlideBitmapDrawable) imageView1.getDrawable();
final Bitmap yourBitmap = bitmapDrawable.getBitmap();
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourBitmap);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
How can i implement click only on image?
In your custom layout xml, set
android:descendantFocusability="blocksDescendants"
to your root layout.
Edit
Check my Custom ListView.
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:gravity="center"
android:descendantFocusability="blocksDescendants"
android:layout_height="60dp">
<ImageView
android:id="#+id/m_imageview"
android:layout_width="0dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"
android:layout_height="50dp" />
<TextView
android:id="#+id/m_textview"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="50dp"
android:gravity="center|center"
android:textColor="#ffffff"
android:text="hello"/>
<Button
android:id="#+id/m_buttonview"
android:layout_width="0dp"
android:layout_weight="2"
android:text="OK"
android:layout_height="50dp" />
</LinearLayout>
activity_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="match_parent" >
<ListView
android:id="#+id/lv_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:dividerHeight="2dp"
android:divider="#ffffff"
tools:context=".MainActivity" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView m_pic;
TextView m_title;
Button m_btn;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.m_title = (TextView) convertView.findViewById(R.id.m_textview);
holder.m_btn = (Button)convertView.findViewById(R.id.m_buttonview);
holder.m_pic = (ImageView) convertView.findViewById(R.id.m_imageview);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.m_title.setText(rowItem.getTxt());
holder.m_pic.setImageResource(rowItem.getImage());
holder.m_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position + " clicked" , Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
RowItem.java
public class RowItem {
private int image;
private String txt;
public RowItem(int imageview , String textview)
{
this.image = imageview;
this.txt = textview;
}
public int getImage() {
return image;
}
public String getTxt() {
return txt;
}
public void setImage(int image) {
this.image = image;
}
public void setTxt(String txt) {
this.txt = txt;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
String m_txt[] = {"one" , "two" , "three" , "four", "five"};
int m_img [] = {R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher};
ListView m_list;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_list = (ListView)findViewById(R.id.lv_items);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < m_txt.length; i++) {
RowItem item = new RowItem(m_img[i],m_txt[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.listitem, rowItems);
m_list.setAdapter(adapter);
m_list.setOnItemClickListener(MainActivity.this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position) + ": " + rowItems.get(position).getTxt(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
This should helps you.
Happy coding.!!!
use a recyclerview.
a recylerview handles every list item as a view, it can hold clicklisteners for every view it holds and that view can hold clicklisteners for every view its holding.
I want to short my code length by using array.If I have 100 button or image view I have to write for 100 . I want to get value from assets folder and pass it in to array . how to use
String[] colorNames = getResources().getStringArray(R.array.colorList);
String[] animalNames = getResources().getStringArray(R.array.animalList);
Current working code :
public class Main extends Activity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag);
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
image = (ImageView) findViewById(R.id.image);
Button btn1,btn2;
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
if(key.equals("animalIntent") )
{
btn1.setText("cat");
btn2.setText("dog");
// same for 100 button ............. here i want to short my code
} else {
btn1.setText("red");
btn2.setText("blue");
}
}
public void btn1(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.cat);
// same for 100 image view ............. here i want to short my code
} else {
image.setBackgroundResource(R.drawable.red);
}
}
public void btn2(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.dog);
} else {
image.setBackgroundResource(R.drawable.blue);
}
}
To do that you should use GridView,it would be best option. try the below sample code.
Step-1 add the gridview in your drag.xml
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/edt"
android:numColumns="2"
android:stretchMode="columnWidth" >
</GridView>
Step-2 Declare the variables and get the grid view reference.
GridView gridview;
Integer[] drawableIds = { R.drawable.poster1, R.drawable.poster2, R.drawable.poster3, R.drawable.poster4,
R.drawable.poster5 };
String[] colorNames = { "poster one", "poster two", "poster three", "poster four", "poster five" };
//In OnCreate() method add
gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new CustomGridAdapter(this, drawableIds, colorNames));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(Main.this, "" + position, Toast.LENGTH_LONG).show();
}
});
Step-3 create a class for grid adapter CustomGridAdapter.class
public class CustomGridAdapter extends BaseAdapter {
private Context context;
private Integer[] drawableitems;
private String[] drawablelabel;
public CustomGridAdapter(Context context, Integer[] drawableitems, String[] drawablelabel) {
this.context = context;
this.drawablelabel = drawablelabel;
this.drawableitems = drawableitems;
}
#Override
public int getCount() {
return drawableitems.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
RecordHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new RecordHolder();
convertView = inflater.inflate(R.layout.grid_item, null);
holder.txtTitle = (TextView) convertView.findViewById(R.id.grid_item_label);
holder.imageItem = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
} else {
holder = (RecordHolder) convertView.getTag();
}
holder.txtTitle.setText(drawablelabel[position]);
holder.imageItem.setImageResource(drawableitems[position]);
return convertView;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
Add custom view for grid grid_item.xml in layout folder.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center" >
</ImageView>
<TextView
android:id="#+id/grid_item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textSize="18sp"
android:textStyle="bold" >
</TextView>
</LinearLayout>
Hope it will help you.
I am new to android and i am working on listview. I am trying to show data using listview in xml and adapter in class file. I am working on following 3 files.
First file: activity_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="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.listpractice.MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
></ListView>
</RelativeLayout>
Second file: row1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight" >
<ImageView
android:id="#+id/icon"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/firstTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:textSize="30sp"
android:text="#string/hello_world"
/>
<TextView
android:id="#+id/secondTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:layout_below="#id/firstTextView"
android:textSize="13sp"
android:text="#string/hello_world"
/>
</RelativeLayout>
Third file: MainActivity.java
package com.listpractice;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
My Problem : Now i want to show data of row1.xml but i don't have dynamic data. how can i show data using third(.class) file.
check out this link it will help http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
either you need to create adapter file
public class CustomBaseAdapter extends BaseAdapter{
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
//TextView txtDesc;
ImageView imgarrow;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
//holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.imgarrow=(ImageView)convertView.findViewById(R.id.arrow_icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
//holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgarrow.setImageResource(rowItem.getImg());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
MainActivity
public class MainActivity extends Activity implements OnItemClickListener{
public static final String[] titles = new String[] { "Krish",
"John Cena", "Kane","Roman Reigns"};
public static final Integer[] images = { R.drawable.fourth,R.drawable.second,R.drawable.first,R.drawable.third};
public static final Integer[] imagearow = {R.drawable.arrow,R.drawable.arrow,R.drawable.arrow,R.drawable.arrow };
ListView listView;
List<RowItem> rowItems;
private ImageView btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_home);
//list_travels=(ListView)findViewById(R.id.list_travels);
btn=(ImageView)findViewById(R.id.btnaddhotels);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Intent i=new Intent(HomeScreen.this,Registerhotel_resorts.class);
startActivity(i);
}
});
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i],imagearow[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list_hotels);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent i1=new Intent(HomeScreen.this,KrishnaParkResort.class);
startActivity(i1);
}
}
You should read this article on Building Layouts with an Adapter. It has some handy concepts which you will need to get your head around.
The fundamental concept is that you need to link your ListView to an Adapter which populates the rows and adds them to the ListView.
Looking at your row1.xml, it looks like you will need a collection of objects which contain;
An image for icon
String for firstTextView
String for secondTextView
You can build a little snippet to create an array of prepopulated objects for test purposes.
public class YourObject {
private Bitmap icon;
private String text1;
private String text2;
public YourObject(Bitmap icon, String text1, String text2) {
this.icon = icon;
this.text1 = text1;
this.text2 = text2;
}
// GETTERS AND SETTERS
}
Then create a collection of them
List<YourObject> data = new ArrayList<>();
for (int z = 0; z < 5; z++) {
YourObject yourObject = new YourObject(yourIcon, "Text1: " + z, "Text2: " + z);
data.add(yourObject);
}
Once you have this collection, you send it to a your Adapter constructor along with the reference to row1.xml, then follow the guide to populate the rows.
I would like to insert a small image to the right of each item in a listview
basically my app should do so as soon as the user clicks on an item in the list view, the image becomes visible, otherwise it must remain invisible.
below is my activity with its XML
Activity
public class EpisodiActivity extends Activity {
public class ViewModel {
private String url;
private String name;
public ViewModel(String url, String name) {
this.url = url;
this.name = name;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//creazione fullscreen activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.episodi_activity);
String[] episodi = getIntent().getStringArrayExtra("Product");
String[] urls = getIntent().getStringArrayExtra("urls");
ListView mylist = (ListView) findViewById(R.id.listView1);
// And in this loop we create the ViewModel instances from
// the name and url and add them all to a List
List<ViewModel> models = new ArrayList<ViewModel>();
for (int i = 0; i < episodi.length; i++) {
String name = episodi[i];
String url = "No value";
if (i < urls.length) {
url = urls[i];
}
ViewModel model = new ViewModel(url, name);
models.add(model);
}
// Here we create the ArrayAdapter and assign it to the ListView
// We pass the List of ViewModel instances into the ArrayAdapter
final ArrayAdapter<ViewModel> adapter = new ArrayAdapter<ViewModel>(this, android.R.layout.simple_list_item_1, models);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Here we get the ViewModel at the given position
ViewModel model = (ViewModel) arg0.getItemAtPosition(position);
// And the url from the ViewModel
String url = model.getUrl();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
XML
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/pubblicita"
android:cacheColorHint="#ffd700"
android:background="#drawable/sfondobottone" />
I think you want this kind of output in listview
text with image in listview
You can use custom listview . Make a class which extends BaseAdapter class
here is the exmaple that i am using
Your BaseAdapter
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FrontListBaseAdapter extends BaseAdapter {
private static ArrayList<FrontDetails> itemDetailsrrayList;
private LayoutInflater l_Inflater;
public FrontListBaseAdapter(Context context, ArrayList<FrontDetails> results) {
itemDetailsrrayList = results;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return itemDetailsrrayList.size();
}
public Object getItem(int position) {
return itemDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// get the views in frontview xml file where you have
// define multiple views that will appear in listview each row
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.frontview, null);
holder = new ViewHolder();
holder.Image = (ImageView) convertView.findViewById(R.id.adminpic1);
holder.MsgType = (TextView) convertView.findViewById(R.id.msgtype1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.Image.setImageResource(R.drawable.mainlogo); // you can set your setter here
holder.MsgType.setText(itemDetailsrrayList.get(position).getMsgType());
return convertView;
}
// holder view for views
static class ViewHolder {
ImageView Image;
TextView MsgType;
}
}
your FrontDetails class where you will make getters and setters and this class will be used in final ArrayList resultse = new ArrayList();
import android.graphics.Bitmap;
public class FrontDetails {
public int getImage() {
return image;
}
public void setImage(int imageN) {
this.image = imageN;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String text) {
this.MsgType = text;
}
private int image;
private String MsgType;
}
your frontview.XML where you put your multiple views that will be in each row or your layout
<?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="100dp"
android:orientation="vertical"
android:layout_margin="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp" >
<ImageView
android:id="#+id/adminpic1"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/msgtype1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:textSize="1sp"
android:text="MsgType" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
and your listview in xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/sync"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sync" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" >
</ListView>
</LinearLayout>
now in your main activity
final ArrayList<FrontDetails> resultse = new ArrayList<FrontDetails>();
FrontListBaseAdapter asdf = new FrontListBaseAdapter(context, resultse);
lv1.setAdapter(new FrontListBaseAdapter(Front.this, resultse));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Object o = lv1.getItemAtPosition(position);
FrontDetails obj_itemDetails = (FrontDetails)o;
Toast.makeText(context, "You have chosen " + ' ' + obj_itemDetails.getMsgType(), Toast.LENGTH_LONG).show();
}
});
EDIT:
From here i learned Custom Listview its a simple exmaple with image
http://www.javasrilankansupport.com/2012/05/android-listview-example-with-image-and.html
http://www.javacodegeeks.com/2012/10/android-listview-example-with-image-and.html
Use custom listview with BaseAdapter
Your Adapter
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
Your list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
Your Single Row item class
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
List view implementation
listView = (ListView) findViewById(R.id.list);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
I can give some tips ,but unfortunately couldn't help you by example..
First of all create one custom adapter(extends BaseAdapter) followed by one custom layout..
Here the custom layout contains the textview and one image view(by default invisible) at the right.
Just customize your list view with your adapter and put text inside TextView through get view()..
At last in your listItemClickListener make the image visible by its position.
You can set here on xml like this
android:visibility="visible"
or
android:visibility="invisible"
or
android:visibility="gone"
Java program:
ImageView imgView = (ImageView)findViewById(R.id.custom);
set your ImageView like this
imgView .setVisibility(View.VISIBLE);
imgView .setVisibility(View.INVISIBLE);
imgView .setVisibility(View.GONE);
Difference between INVISIBLE and GONE.
INVISIBLE - The widget will be invisible but space for the widget will be show.
GONE - Both space and widget is invisible.
Now you can hook your setOnItemClickListener()
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
imgView .setVisibility(View.VISIBLE);
}
});