how to insert an image into a listview? - android

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);
}
});

Related

how to hide/show Imageview on Button Click for Custom Adapter Layout

I have custom adapter for ListView. The ListView is in activity_main.xml and I have a ImageView in CustomAdapter layout which is populated with ListView using CustomAdapter.
My Question is I have to hide/show that image which is in custom layout with a button present in main layout. Like if there is 10 row in my ListView and 10 row have that image. I want to hide only for the particular row.
I hope you understand my question...Thanks in Advance
Here's my ListViewAdapter
public class ListViewAdapter extends ArrayAdapter<FileName> {
Context context;
LayoutInflater inflater;
List<FileName> filenames;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context,int resource,List<FileName> filenames) {
super(context, resource, filenames);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.filenames = filenames;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView filename;
TextView shorttext;
ImageView imageView;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
return view;
}
}
name = filenames.get(position).getName(); //getting the positin from listview
filenames.set(name,FileName.isVisible = true); //getting error on isVisible
I have writen a Sample code and tested
MainActivity
public class MainActivity extends AppCompatActivity {
List<FileName> filenames;
DBhelper dBhelper;dBhelper
SQLiteDatabase sqLiteDatabase;
ListViewAdapter listViewAdapter;
ListView listView;
ImageView lock;
String name;
//temporary button i have added
Button lockBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.lv_filename);
lockBTN = (Button) findViewById(R.id.lock);
filenames = getResult();
listViewAdapter = new ListViewAdapter(this, filenames);
listView.setAdapter(listViewAdapter);
lockBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//giving statically position is 2
int position = 2;
// when you press menu button or any other button
FileName fileName = filenames.get(position);
//here you can set true-Show and false-hide imageview
fileName.setVisible(true);
//and update the list
filenames.set(position, fileName);
listViewAdapter.notifyDataSetChanged();
}
});
}
//temporary data to show on listview
private List<FileName> getResult() {
List<FileName> fileNames = new ArrayList<>();
String[] nameArr = {"Name1", "Name2", "Name3"};
String[] shortTextArr = {"ShortText1", "ShortText2", "ShortText3"};
for(int i=0; i<nameArr.length;i ++){
FileName fileName = new FileName();
fileName.setName(nameArr[i]);
fileName.setShorttext(shortTextArr[i]);
//setting default is hide to imageview
fileName.setVisible(false);
fileNames.add(fileName);
}
return fileNames;
}
}
FileName
public class FileName {
private String name;
private String shorttext;
private boolean visible = true;
public String getName() {
return name;
}
public void setName(String _name) {
this.name = _name;
}
public String getShorttext() {
return shorttext;
}
public void setShorttext(String _shorttext) {
this.shorttext = _shorttext;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
ListViewAdapter
public class ListViewAdapter extends BaseAdapter{
Context context;
LayoutInflater inflater;
List<FileName> filenames;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context, List<FileName> filenames) {
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.filenames = filenames;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filenames.size();
}
#Override
public Object getItem(int position) {
return filenames.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
//holder.filename.setPaintFlags(holder.filename.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
// check weather image is to show/hide
if (filenames.get(position).isVisible()) {
holder.imageView.setVisibility(View.VISIBLE);
} else {
holder.imageView.setVisibility(View.GONE);
}
return view;
}
private class ViewHolder {
TextView filename;
TextView shorttext;
ImageView imageView;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:orientation="vertical">
<ListView
android:id="#+id/lv_filename"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/lock"/>
<Button
android:id="#+id/lock"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Lock"/>
</RelativeLayout>
custom_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/utilities_notepad_icon" />
<LinearLayout
android:layout_width="232dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.77">
<TextView
android:id="#+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="1dp"
android:paddingTop="5dp"
android:text="Item Title"
android:textSize="16dp" />
<TextView
android:id="#+id/item_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="35"
android:paddingBottom="5dp"
android:paddingTop="1dp"
android:text="Item Description"
android:textColor="#999"
android:textSize="10dp" />
</LinearLayout>
<ImageView
android:id="#+id/lock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/lo"
android:layout_marginTop="13sp" />
</LinearLayout>
Take a extra variable in your FileName class.
public class FileName {
public String name;
public String shortText;
public boolean visible = true; // Set the default value to true.
}
Now on external button click in your main layout, you might consider updating the list item accordingly. Just set the visible variable to false of that item you want to hide. Then call notifyDataSetChanged() on your adapter to reload the data.
And yes, in your adapter, just check the value of visible attribute and then decide to hide/show the ImageView. So the getView function of your adapter should look like this.
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
// Hide/Show the ImageView
if (filenames.get(position).visible) holder.imageView.setVisibility(View.VISIBLE);
else holder.imageView.setVisibility(View.GONE);
return view;
}
I would suggest you to use RecyclerView instead of ListView. RecyclerView got more performance than the ListView. Now a days all are using RecyclerView instead of old ListView, it is quite easy to use as well.
And for handling your case create a function to remove the file name you wanted to remove in the RecyclerViewAdapter class as below
removeImageView(position){
fileNames.remove(position);
this.notifyItemRemoved(position);
}
notifyItemRemoved call will refresh the position in the recycler view and you will also get a nice view removing animation out of the box.

Custom List View in Navigation Drawer

I am trying to populate Navigation Drawer with some custom layout. XML file for that layout is below:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
</FrameLayout>
<!-- The navigation drawer -->
<LinearLayout
android:orientation="vertical"
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FFFFFF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="40px"
android:layout_marginTop="40px">
<ImageView
android:id="#+id/imgUser"
android:src="#drawable/empty_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20px"
android:layout_marginTop="20px">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Waqas Ahmed Ansari"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="63km"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Joined: Feb '16"/>
</LinearLayout>
</LinearLayout>
<ListView
android:id="#+id/lstDrawerItems"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice"
android:layout_marginTop="20sp" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Then I made a CustomAdapter class for ListView lstDrawerItems
Here it is.
public class CustomAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
ImageView imgView;
public CustomAdapter(Activity activity, ArrayList<HashMap<String, String>> list) {
super();
this.activity=activity;
this.list=list;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView = inflater.inflate(R.layout.custom_drawer_list, null);
txtFirst = (TextView) convertView.findViewById(R.id.drawer_itemName);
imgView = (ImageView) convertView.findViewById((R.id.drawer_icon));
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get("name"));
imgView.setImageResource(Integer.parseInt(map.get("imgDrawerIcon")));
return convertView;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
When I set list adapter, I am not able to see anything.
I set custom adapter here.
CustomAdapter adapter = new CustomAdapter(HomeNoVehicle.this, list);
ListView drawerList = (ListView) findViewById(R.id.lstDrawerItems);
drawerList.setAdapter(adapter);
But when I set the entries attribute if list, it works well.
Can't figure out what the problem is.
In order to make a custom list, the way that I like to start is design the cell, or cells you wish to display in the list. Something maybe like this:
Then I like to make a Class to go with that cell:
public class ProfileCell extends RelativeLayout {
ImageView imageView;
TextView name;
TextView dateJoined;
TextView distance;
String nameText;
String dateJoinedText;
String distanceText;
public ProfileCell(Context context) {
super(context);
inflate(context, R.layout.nav_list_row, this);
name = (TextView)findViewById(R.id.name);
dateJoined = (TextView)findViewById(R.id.date_joined);
distance = (TextView)findViewById(R.id.distance);
imageView = (ImageView)findViewById(R.id.imgUser);
//set Image to a default value
imageView.setImageResource(R.mipmap.ic_launcher);
}
public String getNameText() {
return nameText;
}
public void setNameText(String nameText) {
this.nameText = nameText;
name.setText(nameText);
}
public ImageView imageView() {
return imageView;
}
public String getDateJoinedText() {
return dateJoinedText;
}
public void setDateJoinedText(String dateJoinedText) {
this.dateJoinedText = dateJoinedText;
dateJoined.setText(dateJoinedText);
}
public String getDistanceText() {
return distanceText;
}
public void setDistanceText(String distanceText) {
this.distanceText = distanceText;
distance.setText(distanceText);
}
}
Then I also find it convenient to make a class that can hold the information that I want to put in that cell:
public class Profile {//Information about Users Profile
public String name;
public String dateJoined;
public String distance;
/////////possibly have image url here ....
public Profile(String name, String dateJoined, String distance)
{
this.name = name;
this.dateJoined = dateJoined;
this.distance = distance;
}
}
Then I make my custom adapter class:
public class CustomAdapter extends BaseAdapter {
ArrayList<Profile> profiles;
Context context;
public CustomAdapter(Context context, ArrayList<Profile> profiles)
{
this.context = context;
this.profiles = profiles;
}
#Override
public int getCount() {
return profiles.size();
}
#Override
public Profile getItem(int position) {
return profiles.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
//Custom Cell is inflated inside of the Profile view class
convertView = new ProfileCell(context);
}
ProfileCell cell = (ProfileCell) convertView;
Profile profile = getItem(position);
cell.setNameText(profile.name);
cell.setDateJoinedText(profile.dateJoined);
cell.setDistanceText(profile.distance);
//Then you would set the image view to something...
// cell.imageView().setImageResource(R.mipmap.ic_launcher);
//something like that maybe
return cell;
}
}
Then if I have set up my list view where I want it, in your case inside a navigation drawer then inside of your navigation activity you can do this:
//A list of data to display in list
ArrayList<Profile> profiles = new ArrayList<>();
for (int i = 0; i < 15; i++)
{
profiles.add(profile);//Adding same profile over an over
}
CustomAdapter adapter = new CustomAdapter(this,profiles);
listView.setAdapter(adapter);
And then this would display whatever you put in those cells.
I put the full code for this up here:
https://github.com/amffz9/NavigationProject

Data not showing in static way using listview

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.

Adding radio button to listview

I would like to add a radio button to my existing listview so that only one radio button needs to be selected at a time.
ItemDetails:
public class ItemDetails {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public int getImageNumber() {
return imageNumber;
}
public void setImageNumber(int imageNumber) {
this.imageNumber = imageNumber;
}
private String name ;
private String itemDescription;
private String price;
private int imageNumber;
}
Adapter:
public class ItemListBaseAdapter extends BaseAdapter {
private static ArrayList<ItemDetails> itemDetailsrrayList;
private Integer[] imgid = {
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6
};
private LayoutInflater l_Inflater;
public ItemListBaseAdapter(Context context, ArrayList<ItemDetails> 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;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.item_details_view, null);
holder = new ViewHolder();
holder.txt_itemName = (TextView) convertView.findViewById(R.id.name);
holder.txt_itemDescription = (TextView) convertView.findViewById(R.id.itemDescription);
holder.txt_itemPrice = (TextView) convertView.findViewById(R.id.price);
holder.itemImage = (ImageView) convertView.findViewById(R.id.photo);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_itemName.setText(itemDetailsrrayList.get(position).getName());
holder.txt_itemDescription.setText(itemDetailsrrayList.get(position).getItemDescription());
holder.txt_itemPrice.setText(itemDetailsrrayList.get(position).getPrice());
holder.itemImage.setImageResource(imgid[itemDetailsrrayList.get(position).getImageNumber() - 1]);
// imageLoader.DisplayImage("http://192.168.1.28:8082/ANDROID/images/BEVE.jpeg", holder.itemImage);
View row = convertView;
CheckedTextView checkBox = (CheckedTextView) row.findViewById(R.id.checkstate);
checkBox.setChecked(false);
return convertView;
}
static class ViewHolder {
TextView txt_itemName;
TextView txt_itemDescription;
TextView txt_itemPrice;
ImageView itemImage;
CheckedTextView checkBox;
}
}
ItemDetails.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/photo"
android:layout_width="150dip"
android:layout_height="100dip"
android:paddingRight="15dp"
android:paddingLeft="15dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="160dp"
android:layout_marginTop="10dp">
<TextView android:id="#+id/name"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/itemDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/name"/>
<TextView android:id="#+id/price"
android:textSize="19sp"
android:textStyle="bold"
android:textColor="#003399"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/itemDescription"/>
</RelativeLayout>
</RelativeLayout>
ListView:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background ="#CCCCCC">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:divider="#3366CC"
android:dividerHeight="2dp"
android:choiceMode="singleChoice"/>
</LinearLayout>
I have seen many SO anwsers but none of them got working in my case saying to add
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
Can anyone say me how to acheive this ?
For complex ListView item, you should do it by yourself. Just add boolean isSelected in your ItemDetails and then checkBox.setChecked(item.isSelected); in your getView() in ItemListBaseAdapter. Now when an item is clicked in ListView just change your the data in itemDetailsrrayList and call notifyDataSetChanged().
I have made my getView() method.Just make radio button instead of simple button.I Hope this helps.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View productListView = null;
productListView = convertView;
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (productListView == null)
productListView = inflater.inflate(R.layout.menu_productlist_list,
parent, false);
productListTitle = (TextView) productListView
.findViewById(R.id.productListTitle);
String title = menuProductListCollection.get(position).getPD_TITLE();
productListTitle.setText(title);
productListCategoryButton = (ImageButton) productListView
.findViewById(R.id.productListCategoryButton);
// Perform Button action on click of each row's button
productListCategoryButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//do your stuff here
}
});
// Perform action on click of each row
productListView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//do your stuff here
}
});
return productListView;
}
I think you should try both of this,
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
And in xml file you need to add,
<ListView
...
android:choiceMode="singleChoice"
... />
Also add this in your radio-button's xml,
<RadioButton
...
android:clickable="false"
android:focusable="false"
... />
Make HashMap m and initialize it
for (HashMap<String, Object> m :list_data) //make data of this view should not be null (hide )
m.put("checked", false);
Now, setViewBinder to adapter
adapter.setViewBinder(new SimpleAdapter.ViewBinder()
{
public boolean setViewValue(View view, Object data, String textRepresentation)
{
if (data == null) //if 2nd line text is null, its textview should be hidden
{
view.setVisibility(View.GONE);
return true;
}
view.setVisibility(View.VISIBLE);
return false;
}
});
It will work like charm.
Check this Example link

ImageView setVisibility(0) and null pointer exception

I have 2 xml files, a main file where I have a listView and the other where I am making some customisations to my listView.
The second xml is used on my Custom ArrayAdapter.
In the second xml i have a ImageView which I would like to set to visible at one moment but I am getting the null pointer exception because i am never setting with setCurrentView the second xml file where is my ImageView.
I am trying to do this:
ImageView statusOk=(ImageView)findViewById(R.id.statusOkImage);
statusOk.setVisibility(0);
Could you please tell me how to resolve that?
Thank you.
Edit:
Here is more code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/ListView01"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
Second xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/statusOkImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/status_ok"
android:visibility="invisible"/>
<TextView android:id="#+id/name"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#FFFF00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/cityState"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity:
public class TestListActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<SearchResults> searchResults = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter(new MyCustomBaseAdapter(this, searchResults));
}
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr1 = new SearchResults();
sr1 = new SearchResults();
sr1.setName("Fred Jones");
sr1.setCityState("Las Vegas, NV");
sr1.setPhone("612-555-8214");
results.add(sr1);
return results;
}
}
custom Adapter:
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.name);
holder.txtCityState = (TextView) convertView.findViewById(R.id.cityState);
holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
mInflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view=mInflater.inflate(R.layout.custom_row_view, null);
ImageView statusOk=(ImageView)view.findViewById(R.id.imageView1);
statusOk.setVisibility(View.VISIBLE);
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtCityState.setText(searchArrayList.get(position).getCityState());
holder.txtPhone.setText(searchArrayList.get(position).getPhone());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtCityState;
TextView txtPhone;
}
}
And finnaly the resource class for the listView
public class SearchResults {
private String name = "";
private String cityState = "";
private String phone = "";
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setCityState(String cityState) {
this.cityState = cityState;
}
public String getCityState() {
return cityState;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
}
To set visibility view defined in xml, you need to inflate that view in activity, setContentView do it automatically, and as you are not invoking setContentView on second xml, then use:
LayoutInflater inflater=(LayoutInflater)getSystemService(Layout_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.secondxml, null);
and then find your view from that view:
ImageView statusOk=(ImageView)view.findViewById(R.id.statusOkImage);
statusOk.setVisibility(0);
but it will work only for view object, it does not affect original xml.
Change to :
statusOk.setVisibility(View.INVISIBLE);
and check is image is ready to use findViewById, like you call the method and after do setContentView or if it really is ImageView, etc.
Here is the solution for accessing the view from another class.
Note : currentActivity is the context of root class
LayoutInflater inflater = (LayoutInflater)currentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.secondxml, null);
Use LayoutInflater.getLayoutInflater() to instantiate layout XML file into its corresponding View objects.
ImageView imgview=(ImageView)findViewById(R.id.imageView1);
imgview.setVisibility(View.INVISIBLE); //for invisibility.
imgview.setVisibility(View.VISIBLE); //make your image visible where ever you want

Categories

Resources