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
Related
I have an ListView with BaseAdapter now I just make some listener to item when I click on item I show some hidden view in item.
Every time I click on some item, I show the hidden view or hide them if views are visible. But the problem I face is that I want to hide the other visible item when the I show a new item.
Here I click on some item and its shows the message date and detail:
Now when I click on other items, I want to hide the first one and show the second, like this:
But here in my code when I click on other item its of course will not hide the previous view. How can I do this trick ?
Simply keep a reference to the last view that was clicked, let's call it mLastViewShown;
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mLastViewShown != null)
hideDetails();
mLastViewShown = view;
showDetails();
}
};
Now you have a variable to hide the details from the last user click.
So you want to hide all item's additional field when you click on some other item. In addition to this you also want to toggle visibility of an item's additional view on click on same item.
Here is your main activity:
public class MainActivity extends AppCompatActivity {
private List<ListData> list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get the toolbar instance
handleListClick();
list.add(new ListData("George","Surgeon"));
list.add(new ListData("Nancy","Dentist"));
list.add(new ListData("Henry","Nurse"));
}
private void handleListClick() {
ListView listView=findViewById(R.id.listView);
final CustomBaseAdapter customBaseAdapter=new CustomBaseAdapter(this,list);
listView.setAdapter(customBaseAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
customBaseAdapter.setCurrentSelected(position);
customBaseAdapter.notifyDataSetChanged();
}
});
}
}
Here is your custom base adapter:
public class CustomBaseAdapter extends BaseAdapter {
private List<ListData> myList = new ArrayList<ListData>();
private LayoutInflater inflater;
private Context context;
private int previousSelected=-1;
public CustomBaseAdapter(Context context, List<ListData> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
public void setCurrentSelected(int currentSelected){
if(previousSelected==currentSelected)
previousSelected=-1;
else
previousSelected=currentSelected;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListData getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
ListData currentListData = getItem(position);
mViewHolder.tvMain.setText(currentListData.getMainText());
if(previousSelected==position){
mViewHolder.tvAdditional.setVisibility(TextView.VISIBLE);
mViewHolder.tvAdditional.setText(currentListData.getAdditionalText());
}else{
mViewHolder.tvAdditional.setVisibility(TextView.GONE);
}
return convertView;
}
private class MyViewHolder {
TextView tvMain, tvAdditional;
public MyViewHolder(View item) {
tvMain = (TextView) item.findViewById(R.id.main_text);
tvAdditional = (TextView) item.findViewById(R.id.additional_text);
}
}
}
Here is your ListData:
public class ListData {
private String mainText;
private String additionalText;
public ListData(String mainText, String additionalText) {
this.mainText = mainText;
this.additionalText = additionalText;
}
public String getMainText() {
return mainText;
}
public void setMainText(String mainText) {
this.mainText = mainText;
}
public String getAdditionalText() {
return additionalText;
}
public void setAdditionalText(String additionalText) {
this.additionalText = additionalText;
}
}
Here is your row_item.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/main_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/additional_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
</LinearLayout>
Here is activity_main.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<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="vertical"
tools:context="com.dexter.stackoverflow.MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
I'm new in android..
I would like to create the different views in Listview using Custom Adapter.
Please suggest me how I can do this.
In first row there will be a single Item and in second row there will be two item and so on..
Please Check the attached screen..
Thanks in advance
Define a custom layout of how you want the list row like this
<?xml version="1.0" encoding="utf-8"?>
<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="#dimen/headerHeightCustRow"
android:background="#FFFFFF"
tools:ignore="HardcodedText" >
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginLeft="#dimen/viewSpace1"
android:text="Varun Mad"
android:textSize="#dimen/logout_textSize"
android:textStyle="bold"
android:textColor="#color/orange_normal" />
<TextView
android:id="#+id/txtCustId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="#dimen/viewSpace3"
android:layout_marginTop="#dimen/viewSpace3"
android:layout_marginRight="#dimen/viewSpace3"
android:text="10549"
android:layout_centerVertical="true"
android:textColor="#color/orange_normal"
android:textSize="15sp" />
<TextView
android:id="#+id/txtPhone"
android:layout_below="#id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/viewSpace1"
android:text="(886)677-8855"
android:textColor="#color/orange_normal"
android:textSize="#dimen/vsText" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/viewSpace1"
android:text="ggg#gmail.com"
android:textSize="#dimen/vsText"
android:layout_below="#id/txtPhone"
android:textColor="#color/orange_normal" />
<View
android:layout_width="fill_parent"
android:layout_height="0.5dip"
android:layout_alignParentBottom="true"
android:background="#color/greyDark" />
here is the adapter class
public class SearchCustomerAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<SearchCustomerItem> objects;
public SearchCustomerAdapter(Context context, ArrayList<SearchCustomerItem> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.search_cust_row, parent, false);
}
SearchCustomerItem p = getProduct(position);
((TextView) view.findViewById(R.id.txtName)).setText(p.customerName);
if (p.customerEmail.compareTo("anyType{}") == 0) {
((TextView) view.findViewById(R.id.txtEmail)).setText("");
} else {
((TextView) view.findViewById(R.id.txtEmail)).setText(p.customerEmail);
}
((TextView) view.findViewById(R.id.txtPhone)).setText(p.customerPhone);
((TextView) view.findViewById(R.id.txtCustId)).setText(p.customerId);
return view;
}
SearchCustomerItem getProduct(int position) {
return ((SearchCustomerItem) getItem(position));
}
#SuppressWarnings("unused")
ArrayList<SearchCustomerItem> getBox() {
ArrayList<SearchCustomerItem> box = new ArrayList<SearchCustomerItem>();
for (SearchCustomerItem p : objects) {
// if (p.box)
// box.add(p);
}
return box;
}
}
and the ITem Class
public class SearchCustomerItem {
public String customerName;
public String customerPhone;
public String customerEmail;
public String customerId;
public SearchCustomerItem(String _cName, String _cPhone, String _cEmail, String _cCustId) {
customerName = _cName;
customerPhone = _cPhone;
customerEmail = _cEmail;
customerId = _cCustId;
}
}
you can initialize the adapter,
add the items in Arraylist and show in the list by using
SearchCustomerAdapter boxAdapter;
ArrayList<SearchCustomerItem> products = new ArrayList<SearchCustomerItem>();
to add items in arraylist
products.add(new SearchCustomerItem("CustomerName","PhoneNo","Cust_EmailId","Cust_Id"));
//Add as many items you want
than
boxAdapter = new SearchCustomerAdapter(SearchActivity.this, products);
list.setAdapter(boxAdapter);
This link might help you. link
You should do it step by step.
Extend Base Adapter class by you Custom Adapter class
Override getView and other related methods
set the adapter to list view adapter.
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);
}
});
I am new to Android development. I have created a custom object in java. How do I render it to screen? I look around and is really confused about the whole Android rendering process.
My object is not a list. It is a tree. I also read about Adapter, Layout and View, but don't understand it. Here is my code:
public class GeoArea {
public String id;
public String name;
public String searchLocation;
public static String searchTerm;
public List<GeoArea> subGeoAreas;
public GeoArea parentGeoArea;
public GeoArea(String id) {
this.id = id;
name = id;
searchLocation = "";
subGeoAreas = new LinkedList<GeoArea>();
}
#Override
public String toString() {
return name;
}
public int size(){
int result = 0;
for(GeoArea curGeoArea:subGeoAreas){
result += curGeoArea.size();
}
return result + 1;
}
}
And here is the Layout I have:
<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=".Activity_GeoAreas" >
<TextView
android:id="#+id/textMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Choose Suburb"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:id=""#+id/geoAreasLayout""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textMain"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
So the idea is to render the main GeoArea into geoAreasLayout, and since it is a tree, each subGeoArea will get rendered in turn.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_geo_areas);
GeoArea.searchTerm = "Bar & Grill";
GeoArea torontoArea = new GeoArea("cityOfToronto");
torontoArea.name = "City of Toronto";
torontoArea.searchLocation = "Toronto, ON";
GeoArea testGeoArea = null;
testGeoArea = new GeoArea("DownTownCore");
testGeoArea.name = "Down Town Core";
testGeoArea.searchLocation = "Downtown Core, Toronto, ON";
testGeoArea.parentGeoArea = torontoArea;
torontoArea.subGeoAreas.add(testGeoArea);
testGeoArea = new GeoArea("AlexandraPark");
testGeoArea.name = "Alexandra Park";
testGeoArea.searchLocation = "Alexandra Park, Toronto, ON";
testGeoArea.parentGeoArea = torontoArea;
torontoArea.subGeoAreas.add(testGeoArea);
// what's next?
}
}
I try to write an Adapter, but I am not even sure what it's for or how to use it:
public class GeoAreaAdapter extends BaseAdapter implements Filterable{
private Context _context;
private int resource;
private GeoArea _myGeoArea;
public GeoAreaAdapter(Context context, int resource, GeoArea myGeoArea) {
_context = context;
_myGeoArea = myGeoArea;
}
public int getCount() {
return _myGeoArea.size();
}
public Object getItem(int position) {
return _myGeoArea;
}
public long getItemId(int position) {
return _myGeoArea.id.hashCode();
}
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout GeoAreaView;
if (convertView == null) {
GeoAreaView = new LinearLayout(_context);
LayoutInflater li = LayoutInflater.from(_context);
convertView = li.inflate(R.layout.layout_geo_area, null);
}
else {
GeoAreaView = (LinearLayout) convertView;
}
TextView name = (TextView) GeoAreaView.findViewById(R.id.txtGeoAreaName);
name.setText(_myGeoArea.name);
return convertView;
}
static class ViewHolder {
TextView name;
RelativeLayout childContainer;
}
#Override
public Filter getFilter() {
return null;
}
}
Firstly your class must be extends from one of Views or ViewGroups classes to render and use it in LinearLayout.like this:
public class GeoArea extends View{
According to this issue after that you can use it in xml Layout file like this:
<?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"
>
<com.example.YourClassName
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mapview"
></com.example.YourClassName>
</LinearLayout>
as you see you must use package name to render your new object in xml layout file.
I've got a custom BaseAdapter and an add button in the main activity. The button opens a dialog with a textbox and you can add new elements to the list that way. The problem is that the list is not refreshing. In the onActivityResult() function I print the number of elements in the list and each time I hit OK in the dialog box the number increases, so I know it's just the refreshing that doesn't work. My BaseAdapter and my activity:
class ListaOrase extends BaseAdapter{
private Activity context;
ArrayList<String> orase;
public ListaOrase(Activity context){
this.context=context;
orase=new ArrayList<String>();
}
public void add(String string){
orase.add(string);
this.notifyDataSetChanged();
}
public View getView (int position, View convertView, ViewGroup list) {
View element;
if (convertView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
element = inflater.inflate(R.layout.lista, null);
}
else element = convertView;
TextView elementLista=(TextView)element.findViewById(R.id.elementLista);
elementLista.setText(orase.get(position));
return element;
}
}
public class WeatherAppActivity extends ListActivity {
Button buton;
ListaOrase lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lista=new ListaOrase(this);
buton=(Button)findViewById(R.id.buton);
lista.add("Bucuresti");
lista.add("Sibiu");
setListAdapter(lista);
}
public void add(View view){
Intent intent=new Intent();
intent.setClass(this, Adauga.class);
startActivityForResult(intent, 0);
}
public void onActivityResult (int requestCode, int responseCode, Intent data){
System.out.println("Apelata");
if(responseCode==1){
lista.add(data.getStringExtra("oras")); // e chiar getText()
System.out.println(lista.getCount());
lista.notifyDataSetChanged();
}
}
}
As you can see, I'm trying to refresh (notifyDataSetChanged();) both when adding a new element (in the BaseAdapter extending class) and in method onActivityResult, after the dialog passes the new element to the main Activity. I repeat, the element IS added to the list because the count increases, it just doesn't refresh.
Thanks for your answers!
It's normal that it doesn't refresh, you are adding an item to "lista" but the adapter keeps its own copy of that list, so or you set again the list in the adapter and then you call notifyDataChanged or you add the new item to the adapter.
Anyway I see couple of weird things, I thing you could semplify everything using an array adapter, you don't need to implement add,etc. I wrote some code simplyfing yours:
public class WeatherAppActivity extends ListActivity {
Button buton;
ItemsAdapter lista;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> initialList = new ArrayList<String>();
initialList.add("Bucuresti");
initialList.add("Sibiu");
lista=new ItemsAdapter(this, initialList);
buton=(Button)findViewById(R.id.button1);
buton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lista.add(""+System.currentTimeMillis()); // e chiar getText()
lista.notifyDataSetChanged();
}
});
setListAdapter(lista);
}
class ItemsAdapter extends ArrayAdapter<String> {
public ItemsAdapter(Context context, List<String> list) {
super(context, R.layout.lista, list);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
}
}
These are the xml that I have used:
main.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="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Button" />
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
lista.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
This is the version of the adapter using a baseadapter:
class ItemsBaseAdapter extends BaseAdapter {
private List<String> items;
private Context mContext;
public ItemsBaseAdapter(Context context, List<String> list) {
items = list;
mContext = context;
}
public void addItem(String str) {
items.add(str);
}
#Override
public View getView(final int position, View row, final ViewGroup parent) {
final String item = (String) getItem(position);
ItemWrapper wrapper = null;
if (row == null) {
row = getLayoutInflater().inflate(R.layout.lista, parent, false);
wrapper = new ItemWrapper(row);
row.setTag(wrapper);
} else {
wrapper = (ItemWrapper) row.getTag();
}
wrapper.refreshData(item);
return row;
}
class ItemWrapper {
TextView text;
public ItemWrapper(View row) {
text = (TextView) row.findViewById(R.id.elementLista);
}
public void refreshData(String item) {
text.setText(item);
}
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
And this is the version of the list item wich also include an imageview on the left:
<?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="horizontal" >
<ImageView
android:layout_height="wrap_content"
android:src="#android:drawable/btn_star_big_on"
android:scaleType="fitCenter"
android:layout_width="wrap_content"
/>
<TextView
android:id="#+id/elementLista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>