Dropdown Spinner in NestedScrollView in Fragment - android

I am making a dropdown menu (spinner) inside a fragment. I also need that page to have a Recyclerview that extends and scrolls with the page, so I use the nested scroll view. Java Code:
Spinner dropdown = root.findViewById(R.id.dropdown);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_spinner_dropdown_item,arrayList);
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getContext(),parent.getItemAtPosition(position).toString(),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Xml Code:
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:paddingBottom="65dp"
tools:context=".ui.dashboard.ShelvesFragment">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Spinner
android:id="#+id/dropdown"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#color/honeyBright"
android:textColor="#545454"
android:spinnerMode="dropdown"
android:layout_margin="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/shelves"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.core.widget.NestedScrollView>
When I run this code it just shows this as the drowpdown: Dropdown Spinner Image
It did work when I used the R.array value and the CharSequence Adapter, but I need it to be an array list and I'm not sure the exact code I used then.
Edit:
I figured out that the ArrayList actually didn't have any items in it, that was why it wasn't showing up. So I just fixed that and it worked fine.

Related

AndroidX Spinner not displaying list

I'm trying to integrate a Spinner into my Layout (it was working well before AndroidX migration).
here is the code:
Spinner spinner_nationalite;
String[] data_nationalite = {"","Française","Suisse","Belge","Allemande"};
#Override
public void onCreate(Bundle savedInstanceState) {
....
spinner_nationalite = (Spinner) findViewById(R.id.update_spinner_nationalite);
ArrayAdapter adapter_nationalite = new ArrayAdapter<String>(this, R.layout.spinner_dropdown_item, data_nationalite);
adapter_nationalite.setDropDownViewResource(R.layout.spinner_dropdown_item);
spinner_nationalite.setAdapter(adapter_nationalite);
spinner_nationalite.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("KAIROSAPP","Nationalite selected: "+data_nationalite[i]);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Here is the spinner_dropdown_item.xml
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee"
android:fontFamily="sans-serif-thin"
android:textSize="17sp"
android:textStyle="bold"
android:background="#FFFFFF"
android:textColor="#000000"/>
And finally the Layout XML
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:id="#+id/update_spinner_nationalite"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView55"/>
I can see the Spinner but there are no data listed and no dropdown visible on click.
I also tried to use AppCompatSpinner from androidx.appcompat.widget.AppCompatSpinner and also use android.R.layout.simple_spinner_dropdown_item instead of the custom one but I have the same result.
For sure I'm missing something....
There is no problem on my side. I ran your code successfully on AndroidX project.

Get a field from Fragment on Adapter and get List from Adapter on Fragment

I'm making a list of checkbox with itens on my adapter and my fragment has one checkBox on the top of the list with "Select All" and on the bottom of the list a textView "x Itens Selected" plus a button.
My problem 1 is how to get this "x": the count of how many checkboxes are checked, because they are on Adapter and the TextView is on Fragment, I can't set it on Adapter.
To get this, I'm using a setOnCheckedChangeListener from the list of checkboxes.
I've tried to get Fragment from Adapter with a lot of ways but without success. Sending on constructor, getting from viewHolder, getting from getSupportFragmentManager(), getFragments(), getFragmentById, getFragmentByTag.
I've tried FragmentObserver also, but it didnt work.
Problem 2: So I've tried to make a list on Adapter with all the checked Itens, but I need to send it to Fragment to manage it. Also, I can't get it from Adapter on Fragment (on onCreateView).
Can someone help please?
My Adapter.java onBindViewHolder:
#Override
public void onBindViewHolder(final PedidoItemRefugadoViewHolder holder, final int position) {
//pedidoItem is each object from the list
final PedidoItem pedidoItem = itensRefugados.get(position);
//checkCadaItemRefugado is each checkbox from Adapter
holder.checkCadaItemRefugado.setText(pedidoItem.getItemPedidoObservacao(context));
holder.checkCadaItemRefugado.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int count = 0;
int size = itensRefugados.size();
for (int i=0; i<size; i++){
if (holder.checkCadaItemRefugado.isSelected()) {
count++;
//itensRefugadosChecked is the new list with all the checked items
itensRefugadosChecked.add(pedidoItem);
}
}
}
});
}
My XML Adapter:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="6dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="false"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="6dp"
android:foreground="?attr/selectableItemBackground">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/frame_layout_notificacao"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<CheckBox
android:id="#+id/check_cada_item_refugado"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Item: Pedido: \nMotivo:"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
My XML Fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="br.com.zapgrafica.appzap.fragments.ItensRefugadosFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="32dp"
android:orientation="horizontal"
android:layout_marginTop="8dp"
android:layout_marginStart="7dp">
<CheckBox
android:id="#+id/check_itens_refugados"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selecionar todos"/>
</RelativeLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/itens_refugados_layout_swipe_to_refresh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="42dp"
android:layout_marginBottom="66dp">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:clipToPadding="false"
android:divider="#null"
android:dividerHeight="0dp"
android:listSelector="#android:color/transparent"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical" />
</android.support.v4.widget.SwipeRefreshLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/txt_itens_refugados_total"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:layout_above="#+id/btn_itens_refugados_total"
android:text=""/>
<Button
android:id="#+id/btn_itens_refugados_total"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/itens_refugados_confirmar"
android:theme="#style/ThemeButtonAjusteOnlineRefugo"/>
</RelativeLayout>
</FrameLayout>
You can do it using interface.
Create your interface class, initialize it in adapter class and implement it in your fragment. So when you will need to send any value to fragment, use method which you have created in interface to send data to fragment. You will get checked checkbox values in fragment. Refer this link. Hope this will help you.

Nothing happens when I click on the Spinner item

I have fetched data from the server from the category class.The getcategories method return the List of String containing spinner items. When I click on the spinner item. Nothing happens. Is there any mistake in my code. Please help.
This is my java code.
public void fetchPropertyType(){
category = new Category(); //Spinner Item model
//categories is a array list of String which contains the items of spinner
categories = category.getCategories(AddPropertyActivity.this);
//Property Type Spinner Adapter
propertyTypeSpinner = (Spinner) findViewById(R.id.property_type_spinner);
Log.e("Test", "Just a test message");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
propertyTypeSpinner.setAdapter(dataAdapter);
propertyTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.e("Test", "Nothing selected on spinner activity");
}
});
}
This is my layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1">
<TextView
android:id="#+id/spinner_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="50dp"
android:gravity="center"
android:text="Property Type"
android:textAlignment="textEnd"/>
<Spinner
android:id="#+id/property_type_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"/>
</RelativeLayout>
You just should do this.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#drawable/border">
<TextView
android:id="#+id/spinner_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginRight="50dp"
android:gravity="center"
android:text="Property Type"
android:textAlignment="textEnd"/>
<Spinner
android:id="#+id/property_type_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"/>
</RelativeLayout>
In the Spinner
Change
android:layout_height="match_parent"
To
android:layout_height="wrap_content"
Because you use android:layout_height="match_parent",so you can't see your list item.And nothing happens.
As you are using
<Spinner
android:id="#+id/property_type_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"/>
Which wraps the height of spinner so try to give custom height to it so that i t will be clickable
I did this
<Spinner
android:id="#+id/property_type_spinner"
android:layout_width="match_parent"
android:layout_height="50dp"
android:spinnerMode="dropdown"/>
and keep your text view height wrap_content as
<TextView
android:id="#+id/spinner_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:gravity="center"
android:text="Property Type"/>

Android spinner vertical offset changed

I'm using a Spinner below a title (TextView). It is initially set to View.GONE and when the title is clicked, Spinner is set to View.VISIBLE and the popup window is shown using performClick() below the title, which is what I want.
But I asynchronously update the BaseAdapter to add more items to the Spinner when it is still VISIBLE. After the update the Spinner is moved upwards and is overlaying on the title. How can I fix this?
I have used android:dropDownVerticalOffset, but shows the same behaviour after update.
My layout :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/some_other_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<android.support.v7.widget.AppCompatSpinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:background="#null"
android:overlapAnchor="true"
android:spinnerMode="dropdown"
android:visibility="gone"></android.support.v7.widget.AppCompatSpinner>
</FrameLayout>
</LinearLayout>
Ok.
I Tried running you problem with some slight adjustments on my mobile, and I find no issues.
To simulate your asynchronous addition of items, I added a button.It's OnClick will add items to the adapter.
Next, Instead of extending BaseAdapter, I just used an ArrayAdapter.
And, I just added weights to the LinearLayout to help me with the layout look.
Here Is The Layout :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Title"
android:textSize="20dp"
android:gravity="center"
android:textColor="#android:color/black"
/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
>
<LinearLayout
android:id="#+id/some_other_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<android.support.v7.widget.AppCompatSpinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:background="#null"
android:overlapAnchor="true"
android:spinnerMode="dropdown"></android.support.v7.widget.AppCompatSpinner>
</FrameLayout>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="Load Adapter"
android:id="#+id/button"
/>
</LinearLayout>
And Here Is the Code for the Activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
Spinner spinner;
Button button;
#Override
protected void onResume() {
super.onResume();
spinner = (Spinner) findViewById(R.id.spinner);
button = (Button) findViewById(R.id.button);
List<String> list = new ArrayList<>();
list.add(getRandomStringInRange('A','Z',5));
ArrayAdapter<String> adapter= new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinner.getAdapter();
adapter.add(getRandomStringInRange('A','Z',5));
}
});
}
public int getRandomNumberInRange(int lower,int higher){
int range = higher-lower;
range=(int)(range*Math.random());
return lower + range;
}
public String getRandomStringInRange(char lower,char higher,int length){
String str ="";
for(int i=0;i<length;i++)
str+=(char)(getRandomNumberInRange(lower,higher));
return str;
}
}
I did not find the spinner overlapping the title or it moving at all.
It's working fine.
If you want,I'll send you screenshots.
Please tell me if you are facing any other issues
I couldn't really find a solution for this. But solved by setting fixed height for the spinner as mentioned in this solution.
Spinner spinner = (Spinner) findViewById(R.id.spinner);
try {
Field popup = Spinner.class.getDeclaredField("mPopup");
popup.setAccessible(true);
// Get private mPopup member variable and try cast to ListPopupWindow
android.widget.ListPopupWindow popupWindow = (android.widget.ListPopupWindow) popup.get(spinner);
// Set popupWindow height to 500px
popupWindow.setHeight(500);
}
catch (NoClassDefFoundError | ClassCastException | NoSuchFieldException | IllegalAccessException e) {
// silently fail...
}

ListView item not found

My app is using landscape full screen mode and the navigation drawer. I am using listView in my app along with an edittext. The edittext is the search bar that will search the listview. Both the listview and the edittext are in the navigation drawer. But, when there is no list item that matches the searched word, the listview gets empty.
So how can I add a "Item not found" message instead of the blank listview?
I searched a lot on the internet and found a method setEmptyView(); but I couldn't understand it and hence it is not working. Please help me! Maybe this question is already asked here but please give me an easy explanation.
Here is my code:
MainActivity.java
public class MainActivity extends FragmentActivity {
final String[] data = {"Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Flourine","Noen","Sodium","Magnesium","Aluminium","Silicon","Phosphorous","Sulphur","Chlorine","Argon","Potassium","Calcium","Scandium","Titanium","Vanadium","Chromium","Manganese","Iron","Cobalt","Nickel","Copper","Zinc","Gallium","Germanium","Arsenic","Selenium","Bromine","Krypton","Rubidium","Strontium","Yttrium","Zirconium","Niobium","Molybdenum","Technetium","Ruthenium","Rhodium","Palladium","Silver","Cadmium","Indium","Tin","Antimony","Tellurium"};
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final EditText searchBar = (EditText) findViewById(R.id.searchbar);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.left_drawer_layout);
navList.setAdapter(adapter);
searchBar.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
}
});
//the code below will automatically close the keyboard when the user will touch the listview
navList.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(navList.getWindowToken(), 0);
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
}
}
mainactivity.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Swipe from the left to open the drawer"
android:id="#+id/textView"
android:layout_gravity="center" />
</FrameLayout>
<LinearLayout
android:id="#+id/left_drawer_layout"
android:layout_height="fill_parent"
android:layout_width="240dp"
android:background="#111"
android:orientation="vertical"
android:layout_gravity="start" >
<EditText
android:id="#+id/searchbar"
android:layout_width="230dp"
android:layout_height="40dp"
android:textColor="#bfc2d1"
android:singleLine="true"
android:padding="10dp"
android:background="#drawable/search_bar"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:imeOptions="flagNoExtractUi"
android:hint=" search" >
</EditText>
<TextView
android:id="#+id/notfound"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
style="#android:style/TextAppearance.Medium"
android:gravity="center">
</TextView>
<ListView android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Yes you have mentioned about setEmptyView() correctly, you should use it if you would want to show empty message whenever ListView gets empty.
Now here is a xml layout and code depicts how to use setEmptyView exactly.
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/layoutTitlebar" >
<ListView
android:id="#+id/listViewFriends"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/friendBGColor"
android:cacheColorHint="#00000000" >
</ListView>
<TextView
android:id="#+id/empty"
style="#android:style/TextAppearance.Large"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="#string/strNoRecordsFound" >
</TextView>
</LinearLayout>
Now, you have to set this empty view (i.e. TextView) to ListView by using:
ListView listViewFriends = (ListView) findViewById(R.id.listViewFriends);
// set your adapter here
// set your click listener here
// or whatever else
listViewFriends.setEmptyView(findViewById(R.id.empty));
This method is all that you need
http://developer.android.com/reference/android/widget/AdapterView.html#setEmptyView(android.view.View)
Have in mind it accepts a view, so you have to inflate the layout and fill out any/all text you may have there by yourself.
EDIT:
Let's assume you have a layout named "empty_text" 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="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="There are no entries in this list"
android:gravity="center"/>
</LinearLayout>
Hint: I burned in the string for example purposes, heed the IDE warning and use a string identifier for I18n's sake
Now you would use this code to make it all work with the ListView:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View emptyTextView = inflater.inflate(R.layout.empty_text, null, false);
listView.setEmptyView(emptyTextView);
This code assumes you are executing inside an Activity, but just in case you don't plan on pasting it on an Activity, any Context instance will work.
That should be it.
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.
Detailed Solution:
Layout:
<ListView
android:id="#+id/listViewFriends"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#color/friendBGColor"
android:cacheColorHint="#00000000">
</ListView>
<TextView
android:id="#+id/empty"
android:text="#string/strNoRecordsFound"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
style="#android:style/TextAppearance.Large"
android:gravity="center">
</TextView>
</LinearLayout>
Class File:
ListView listViewFriends = (ListView) findViewById(R.id.listViewFriends);
listViewFriends.setEmptyView(findViewById(R.id.empty));
Source

Categories

Resources