I have been working on trying to implement two listviews inside a list fragment, I have stated two list views in my xml and tried to set two seperate sets of data in the java file but the list view data intended for the first lisview is overwritten by the second.
How would I be able to point it to the correct listviews using the code below?
Java for fragment where list should go:
package com.owais.shopsellswap;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
public class Fragment_My_Profile extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myProfileView = inflater.inflate(R.layout.fragment_my_profile, container, false);
return myProfileView;
}
// Store Arralist as hashmaps for the listview
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
ArrayList<HashMap<String,String>> list2 = new ArrayList<HashMap<String,String>>();
// SimpleAdapter (listViewAdapter) links the array to the listview
private SimpleAdapter listViewAdapter;
private SimpleAdapter listViewAdapter2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//HashMap links each line of data to the correct TextView
HashMap<String,String> item;
for(int i=0;i<userInfo.length;i++){
item = new HashMap<String,String>();
item.put( "line1", userInfo[i][0]);
item.put( "line2", userInfo[i][1]);
list.add( item );
}
HashMap<String,String> item2;
for(int i=0;i<ListingsArray.length;i++){
item2 = new HashMap<String,String>();
item2.put( "line1", ListingsArray[i][0]);
item2.put( "line2", ListingsArray[i][1]);
item2.put( "line3", ListingsArray[i][2]);
list2.add( item2 );
}
listViewAdapter = new SimpleAdapter(getActivity(), list,
R.layout.listview_layout_1,
new String[] { "line1","line2" },
new int[] {R.id.line_a, R.id.line_b});
listViewAdapter2 = new SimpleAdapter(getActivity(), list2,
R.layout.listview_layout_3,
new String[] { "line1","line2", "line3" },
new int[] {R.id.line_a1, R.id.line_b1, R.id.line_c1});
setListAdapter(listViewAdapter);
setListAdapter(listViewAdapter2);
}
private String[][] userInfo =
{{"User","Dummy"},
{"Email Address","Dummy#dummymail.com"},
{"User Type","Staff"},
{"Contact Number","07111111111"}};
private String[][] ListingsArray =
{{"audi a3","brand new audi a3 with alloywheels, cd player", "£11000"},
{"HTC One x","brand new android smartphone", "£450"},
{"Acer Laptop","Acer Laptop with windows 7", "£300"},
{"Sunglass","Oakley Sunglasses in great condition", "£100"}};
}
xml for the fragment:
<?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"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/lightgrey"
android:text="#string/userInfoHeader"
android:textSize="15sp"
android:textStyle="bold" />
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="184dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2" >
</ListView>
<TextView
android:id="#+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/android:list"
android:background="#color/lightgrey"
android:text="#string/listingsHeader"
android:textSize="15sp"
android:textStyle="bold" />
<ListView
android:id="#+id/android:list2"
android:layout_width="fill_parent"
android:layout_height="184dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
</ListView>
</RelativeLayout>
The list view also uses a custom layout for each list.
You need to set the two adapters accordingly with each ListView....
ListView list = (ListView)findViewById(R.id.list);
ListView list2 = (ListView)findViewById(R.id.list2);
list.setAdapter(...)
list2.setAdapter(...)
...however you do not have two ListViews in play. In using a ListFragment each time you call setAdapter you are setting a single ListView to the given contents. You would need to adjust your ListFragement to be that of a Fragment and have two separate ListViews within the Fragment, then set each with its own adapter as mentioned above.
setListAdapter assumes the default target. To set the second adapter you need to find the second listview id and then set the second adapter to it.
listview = findViewById(R.id.list2);
listview.setAdapter(adapter2);
Note that a listfragment usually expects only a single list so the above.might not work, you may need to just use a regular fragment and do the above.for both lists.
Related
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String[] names = new String[]{"name1", "name2", "name3"};
private String[] says = new String[]{"desc1", "desc2", "desc3"};
private int[] imgIds = new int[]{R.mipmap.head_icon1, R.mipmap.head_icon2, R.mipmap.head_icon3};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Map<String, Object>> listitem = new ArrayList<Map<String, Object>>();
for (int i = 0; i < names.length; i++) {
Map<String, Object> showitem = new HashMap<String, Object>();
showitem.put("touxiang", imgIds[i]);
showitem.put("name", names[i]);
showitem.put("says", says[i]);
listitem.add(showitem);
}
//create one simpleAdapter
SimpleAdapter myAdapter = new SimpleAdapter(getApplicationContext(), listitem, R.layout.list_item, new String[]{"touxiang", "name", "says"}, new int[]{R.id.imgtou, R.id.name, R.id.says});
ListView listView = (ListView) findViewById(R.id.list_test);
listView.setAdapter(myAdapter);
}
}
list_item.xml
<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:id="#+id/imgtou"
android:layout_width="64dp"
android:layout_height="64dp"
android:baselineAlignBottom="true"
android:paddingLeft="8dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:textColor="#1D1D1C"
android:textSize="20sp" />
<TextView
android:id="#+id/says"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8px"
android:textColor="#B4B4B9"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
but these images can be recognized by android studio.
anyone can help to find the problem?
You've used SimpleAdapter in your code.
But usage was wrong.
SimpleAdapter haven't image id as parameter.
Please look following URL.
https://developer.android.com/reference/android/widget/SimpleAdapter
public SimpleAdapter (Context context,
List<? extends Map<String, ?>> data,
int resource,
String[] from,
int[] to)
context(Context): The context where the View associated
with this SimpleAdapter is running data List: A List of Maps. Each
entry in the List corresponds to one row in the list. The Maps
contain the data for each row, and should include all the entries
specified in "from"
resource(int): Resource identifier of a view
layout that defines the views for this list item. The layout file
should include at least those named views defined in "to"
from(String): A list of column names that will be added to the Map
associated with each item.
to(int): The views that should display
column in the "from" parameter. These should all be TextViews. The
first N views in this list are given the values of the first N
columns in the from parameter.
But you used image ids array to "to" fields.
//create one simpleAdapter
SimpleAdapter myAdapter = new SimpleAdapter(
getApplicationContext(),
listitem,
R.layout.list_item,
new String[]{"touxiang", "name", "says"},
new int[]{R.id.imgtou, R.id.name, R.id.says} //You used wrong values. This should be textview ids.
);
So you cannot use SimpleAdapter with your purpose.
You should customize Adapter class to your purpose.
SimpleAdapter myAdapter = new SimpleAdapter(
getApplicationContext(),
listitem,
R.layout.list_item,
new String[]{"touxiang", "name", "says"},
new int[]{R.mipmap.head_icon1, R.mipmap.head_icon2, R.mipmap.head_icon3}
);
Or you can use Picasso Library for setting and Loading Images.
I have a 2-column row layout that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:textSize="13sp">
<TextView android:id="#+id/TRAIN_CELL"
android:layout_width="275dip"
android:layout_height="wrap_content"/>
<ImageView android:id="#+id/TO_CELL"
android:layout_width="25dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:src="#drawable/arrow_button"/>
</LinearLayout>
And once I fetch items from the database, I display them in the left column, and in the right column I want to have a little image with an arrow signifying that it is a clickable item. But I am not sure how to make the image render. Here is how I currently populate that list:
I have these two variables:
private List<HashMap<String, String>> fillMaps;
private SimpleAdapter adapter;
At first I set them up like this:
list = (ListView) findViewById(android.R.id.list);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//HashMap<String, String> map = new HashMap<String, String>();
// My data
fillMaps = new ArrayList<HashMap<String, String>>();
adapter = new SimpleAdapter(this, fillMaps, R.layout.questions_list,
new String[] {"train", "to"},
new int[] {R.id.TRAIN_CELL, R.id.TO_CELL});
// This was the middle item R.id.FROM_CELL,
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
and when the data comes back from the server, I populate the list like this:
if ( obj != null )
{
questions.clear();
for ( int i = 0; i < obj.length(); i++ )
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject o = obj.getJSONObject(i);
question_id = o.getString("question_id");
question = o.getString("question");
question_by_member_id = o.getString("member_id");
Question q = new Question ( );
q.setQuestion( question );
q.setQuestionId( question_id );
q.setQuestionByMemberId(question_by_member_id);
map.put("train", question);
//map.put("from", ">");
//map.put("to", ">");
fillMaps.add(map);
questions.add( q );
}
adapter.notifyDataSetChanged();
}
But I am not getting the image to render. I think part of the problem is that I am using Strings as the data that the list expects, but I am not sure how to handle this with the images. The image is always the same image by the way.
Thanks!! :)
Is this what you want?
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:textSize="13sp">
<TextView android:id="#+id/TRAIN_CELL"
android:layout_width="275dip"
android:layout_height="wrap_content"/>
<ImageView android:id="#+id/TO_CELL"
android:layout_width="25dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:src="#drawable/arrow_button"/>
</LinearLayout>
Addition
(Sorry, sometimes I miss notifications when they pile up over night. I believe you should be able to read messages / remove notifications here on Stack Overflow one by one or all at once, like an inbox...)
Anyway, if TO_CELL's image is always going to be the same, simply set the image in the XML only. Change your SimpleAdapter to this:
adapter = new SimpleAdapter(this, fillMaps, R.layout.questions_list,
new String[] {"train"},
new int[] {R.id.TRAIN_CELL});
Now your adapter only handles one string, you can simplify it to an ArrayAdapter (if you want.)
Simplified Example
You can also display one TextView and display a small "next" arrow like so:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="#android:drawable/ic_media_play"
android:padding="10sp"
android:textAppearance="?android:attr/textAppearanceMedium" />
(A LinearLayout and separate ImageView is not strictly necessary. I saved this as list_item.xml.)
Here is a simple preview, understand that I left a lot of the non-critical lines out to not be repetitive:
public class Example extends Activity {
ArrayAdapter<String> adapter;
List<String> list = new ArrayList<String>();
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.text, list);
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
updateList();
}
public void updateList() {
...
if ( obj != null ) {
questions.clear();
list.clear();
for ( int i = 0; i < obj.length(); i++ ) {
JSONObject o = obj.getJSONObject(i);
...
question = o.getString("question");
list.add(question);
}
adapter.notifyDataSetChanged();
}
}
}
Hope this helps!
I believe the easiest way is instead of using a SimpleAdapter try extending the ArrayAdapter for your needs. You can override the getView() method and populate your list the way you need!
There are a few examples here, here and here.
EDIT
First, you need a few modifications in your xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:textSize="13sp">
<TextView android:id="#+id/TRAIN_CELL"
android:layout_width="275dip"
android:layout_height="wrap_content"/>
<ImageView android:id="#+id/TO_CELL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#fff"/>
</LinearLayout>
In the following code I used a ArrayList of Strings for simplicity. You will have to replace that with a list of whatever object you are using to populate your list. (Question maybe?)
Create an ExtendedAdapter and override the getView() method to do what you intend. This will create a TextView and a ImageView on each row of the list, populate the TextView with the items in your ArrayList items and show the image if the item is clickable. (You have to do the verification by yourself but shouldn't be hard to figure it out)
public class ExtendedAdapter extends BaseAdapter {
public static final String TAG = "TodoAdapter";
private Context mContext;
private int layoutResource;
private boolean clickable = false;
private List<String> items; // you can replace this list with whathever you need
// for simplicity i'm assuming you already have the strings
// you need for the textviews
public ExtendedAdapter(Context context, int textViewResourceId,
List<String> items) {
this.items = items;
this.mContext = context;
this.layoutResource = textViewResourceId;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(layoutResource, null);
}
ImageView arrow = (ImageView) v.findViewById(R.id.TO_CELL);
TextView text = (TextView) v.findViewById(R.id.TRAIN_CELL);
text.setText(items.get(position));
if (clickable) // here you have to do your check if it's clickable or not
arrow.setBackgroundResource(R.drawable.ic_launcher);
return v;
}
}
And in your activity, just set the list adapter
public class MainActivity extends Activity {
ListView yourList;
ArrayList<String> itemList = new ArrayList<String>();
ExtendedAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourList = (ListView) findViewById(R.id.yourList);
adapter = new ExtendedAdapter(this, R.layout.row_layout, itemList);
yourList.setAdapter(adapter);
updateItems();
}
public void updateItems(){
//dummy method, you should fetch your data and populate your array in a separate thread
//or something
itemList.add("Text 1");
itemList.add("Text 2");
itemList.add("Text 3");
itemList.add("Text 4");
itemList.add("Text 5");
itemList.add("Text 6");
adapter.notifyDataSetChanged();
}
}
That's how you create a list with text and image.
Good luck!
I think you should customize the list adapter and it will be easy this way.
The problem is with Layout and with the Simple adpater.
1.do not use linearLayout android:textSize="13sp" use it for TextView,
you can use below code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="6dip"
android:paddingTop="4dip" >
<TextView
android:id="#+id/TRAIN_CELL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="try out by yourself..."
android:textSize="13sp" />
<ImageView
android:id="#+id/TO_CELL"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".05"
android:gravity="center"
android:src="#android:drawable/arrow_down_float" />
</LinearLayout>
2.The problem is in SimpleAdapter use
adapter = new SimpleAdapter(this, fillMaps, R.layout.questions_list,
new String[] {"train"},
new int[] {R.id.TRAIN_CELL});
I was trying a simple list view in android.
I got an example from some website. It worked. Code below:
Main Layout File: (res/layout/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:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainListView">
</ListView>
</LinearLayout>
Row File: (res/layout/simplerow.xml)
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
Main Activity:
package com.windrealm.android;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SimpleListViewActivity extends Activity {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// Create and populate a List of planet names.
String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune"};
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
// Add more planets. If you passed a String[] instead of a List<String>
// into the ArrayAdapter constructor, you must not add more items.
// Otherwise an exception will occur.
listAdapter.add( "Ceres" );
listAdapter.add( "Pluto" );
listAdapter.add( "Haumea" );
listAdapter.add( "Makemake" );
listAdapter.add( "Eris" );
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
}
}
I was trying to add an image, not even dynamic. I just thought of adding a layout into the simplerow.xml file. But its not working.
Code below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:contentDescription="#string/songs"
android:src="#drawable/song_bg" />
<ImageView
android:id="#+id/albumArt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:contentDescription="#string/album"
android:src="#drawable/albumart_shanghai" />
<TextView
android:id="#+id/rowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/albumArt"
android:layout_toRightOf="#+id/albumArt"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/black" />
<ImageButton
android:id="#+id/imageView3"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#null"
android:contentDescription="#string/arrow"
android:src="#drawable/arrow_icon" />
</RelativeLayout>
We can't add the Relative layout inside the ListView ?
Pls help me I'm struck with ListView from one month. I couldn't even move a single step :(
I'm newbie to java and XML. Pls someone show me the right path.
First of all you need to extend the ListActivity, like
public class MyListActivity extends ListActivity{}
then you can simply specify the adapter as
setListAdapter(adapter);
You have a problem with your layout file, android list view id should be #android:id/list, android developer site says
your own view MUST contain a ListView object with the id
"#android:id/list"
EDIT
Basically the array adapter constructor signature you are using is,
ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
But if you want to use more complex layout, use
public ArrayAdapter (Context context, int resource, int textViewResourceId, List<T> objects)
where textViewResourceId should refer to the textview id in the layout.
This obviously results in, you can have the layout with multiple text fields but the given texts will be displayed in the textfield specified by the id.
Thus, to get your task done, you need to create your own adapter which extends the BaseAdapter. Within that adapter you need to override the
public View getView(int position, View convertView, ViewGroup parent) {}
method, in which you can inflate your layout and set the appropriate values.
I think you would have gotten at least some idea by this, then take a look on this most explained tutorial about listview.
Vogella given a perfect understanding. please go through it. Its giving you even step by step information.
ListView Example
Layout File:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
Main Activity:
public class MainActivity extends ListActivity {
static final String[] NUM= new String[] { "1", "2", "3",
"4", "5", "6", "7", "8",
"9", "10", "11", "12", "13" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_num,NUM));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
I'm setting a TextView with the id #android:id/empty to display a message when there are no items in the ListView. However, this TextView gets displayed even if there are items in the ListView, right before the items show up.
How can I make it such that it only gets displayed when there are no elements in the ListView?
<?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" >
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:dividerHeight="1dp" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/empty_list" />
</LinearLayout>
PS: I'm using a Loader and a SimpleCursorAdapter with a ListFragment.
I'm guessing you are using a regular Fragment or Activity with a ListView inside of it. If you are, you must add the empty layout to the ListView manually.
E.g.
ListView lv = (ListView)findViewById(android.R.id.list);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
lv.setEmptyView(emptyText);
Then your ListView will automatically use this view when its adapter is empty
If you are using a ListActivity you do not need to call setEmptyView() on the ListView since the ListActivity automatically manages that for you.
Set a TextView and assign to it whatever you want to display when the ListView is empty:
ProjectListAdapter projectListAdapter = new ProjectListAdapter();
TextView empty=(TextView)findViewById(R.id.empty);
projectsListView.setEmptyView(empty);
And in my xml file we write the below code
<TextView
android:id="#+id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Your text here"
android:textColor="#FFFFFF" />
I had this problem. You have to set the emptyView explicitly in your code.
Change your TextView:
<TextView
android:id="#+id/emptyResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/empty_list" />
Then in the onCreate():
listViewResults = (ListView) findViewById(R.id.list);
listViewResults.setEmptyView((LinearLayout) findViewById(R.id.emptyResults));
This code above assumes your ListView is in a LinearLayout.
I used ListFragment and had the same issue. I tried all variants from this answers, but the problem wasn't solved.
So I found my variant, to override setEmptyText():
public class NewsFragment extends ListFragment{
private TextView emptyText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//...
emptyText = (TextView)view.findViewById(android.R.id.empty);
//...
}
#Override
public void setEmptyText(CharSequence text) {
emptyText.setText(text);
}
}
Hope it will be helpful for somebody.
I know this is kind of late, but for it to work from XML, you need to put a weight on your ListView and have your TextView match_parent
<?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" >
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:dividerHeight="1dp" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/empty_list" />
</LinearLayout>
There's a good example of how to do it which works awesome:
When you want to show a message to the user when the ListView is
empty, you have to keep in mind the following 3 steps:
In the xml where the ListView is declared, create a TextView (the TextView can be inside a LinearLayout if you want) right
below the ListView
Set the TextView’s id as “emptyElement”
And inside the activity, set the setEmptyView() property to the ListView
1- Create an xml which will hold the ListView and name it
“my_activity”
and an activity called “MyActivity”.
Now, in the just created xml “my_activity”, you will have to set the ListView. And right below the ListView, you will have to add
a TextView. This will be used to display the empty message.
Important: The TextView must have as id the following name: “emptyElement”. This name is mandatory. The message won’t be displayed
if you use another name.
This is how “my_activity” xml should look like:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/emptyElement"
android:text="The list is empty"
android:textStyle="bold"
android:textSize="15sp"
android:visibility="gone"
android:layout_centerInParent="true"
android:textColor="#android:color/darker_gray"/>
</RelativeLayout>
Create an xml for displaying items (when the list is not empty), and name it “list_item”.
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_item_text_view"
android:textSize="20sp"
android:padding="10dp"
android:layout_marginLeft="5dp"/>
Create a new Java class for the custom adapter which will be used by the ListView and name “MyCustomAdapter”. The code for the adapter
is written below:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mListItems;
private LayoutInflater mLayoutInflater;
public MyCustomAdapter(Context context, ArrayList<String> arrayList){
mListItems = arrayList;
//get the layout inflater
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
//getCount() represents how many items are in the list
return mListItems.size();
}
#Override
//get the data of an item from a specific position
//i represents the position of the item in the list
public Object getItem(int i) {
return null;
}
#Override
//get the position id of the item from the list
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
// create a ViewHolder reference
ViewHolder holder;
//check to see if the reused view is null or not, if is not null then reuse it
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.list_item, null);
holder.itemName = (TextView) view.findViewById(R.id.list_item_text_view);
// the setTag is used to store the data within this view
view.setTag(holder);
} else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)view.getTag();
}
//get the string item from the position "position" from array list to put it on the TextView
String stringItem = mListItems.get(position);
if (stringItem != null) {
if (holder.itemName != null) {
//set the item name on the TextView
holder.itemName.setText(stringItem);
}
}
//this method must return the view corresponding to the data at the specified position.
return view;
}
/**
* Static class used to avoid the calling of "findViewById" every time the getView() method is called,
* because this can impact to your application performance when your list is too big. The class is static so it
* cache all the things inside once it's created.
*/
private static class ViewHolder {
protected TextView itemName;
}
}
Now go to MyActivity class and add the code below:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
ListView listView = (ListView) findViewById(R.id.listView);
// Create an empty array list of strings
List<String> items = new ArrayList<String>();
// Set the adapter
MyCustomAdapter adapter = new MyCustomAdapter(items);
listView.setAdapter(adapter);
// Set the emptyView to the ListView
listView.setEmptyView(findViewById(R.id.emptyElement));
}
}
TextView tv=(TextView) view.findViewById(R.id.empty);
tv.setVisibiliy(View.GONE);
The requirement for my screen is like having a title bar at the top middle and followed by the list view when am trying to do that am not able to do like i got state name in every list item.I want that only in the top and once. And the screen shot of it is
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#000000"
android:text="Select State"
></TextView>
</TableRow>
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="#+id/label"
android:textSize="30px"></TextView>
</TableRow>
</TableLayout>
I have tried many ways this is my present layout
and my java code is
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class new21 extends ListActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "Andhra Pradesh", "Kerala","Tamilnadu","Karnataka" };
// Use your own layout and point the adapter to the UI elements which
// contains the label
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.new21,
R.id.label, names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
if(keyword.equals("Andhra Pradesh"))
{
Intent ima45=new Intent(new21.this,new31.class);
startActivity(ima45);
}
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
Can any one help me.
You can addHeader to the ListView like this,
View header = getLayoutInflater().inflate(R.layout.header, null);
ListView listView = getListView();
listView.addHeaderView(header);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, names));
Where R.layout.header is the layout that contains a TextView with text "Select State"
UPDATED:
public class ListViewProblemActivity extends ListActivity {
ListView listView;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "Andhra Pradesh", "Kerala","Tamilnadu","Karnataka" };
// Use your own layout and point the adapter to the UI elements which
// contains the label
TextView tv = new TextView(getApplicationContext());
tv.setText("Select State");
listView = getListView();
listView.addHeaderView(tv);
this.setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
if(position != 0){
System.out.println(position - 1);
Object o = this.getListAdapter().getItem(position - 1);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
}
Usey only a ListView in your activity, remove the heading there. Then use ListView.addHeaderViwe(); to add a header to the Listview. This Header is display before the first item.
See the documentaton for further information.
you better use ListView.addHeaderViwe();
but don't forget to remove what u did "extends ListActivity", no need for that,
and also remove title from your "new21.xml"
in your xml, just fix the text item u want to show in every row of the list,
You are doing fully wrong. Just take a LinearLayout with one TextView (for Title bar) and ListView (To display listview), nothing more than these 2 views.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#000000"
android:text="Select State">
</TextView>
<ListView
android:id="#+id/lviewState"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>
Now, follow your code to display ListView.