问题
I seem to have problems using custom styles for ListView.
All online searches (stackOverflow and other sites) pty much say the same: - create an my_style.xml layout file. - use it in the adapter.
But for some reason this doesn't seem to be working for me. MainAct.java:
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.list_content, items);
XML file:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0000DD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
saved as /res/layout/list_content.xml.
If I use the android.R.layout.simple_list_item_1 everything works fine, with the own xml file I get "java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView".
Any ideas?
PS: I already looked at lots of other very similar questions/issues, including:
"ArrayAdapter requires the resource ID to be a TextView" xml problems
How to set the text at center in ListView android application?
Android ListView Text Color
回答1:
As error java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
clearly says. You need to pass the textview on which you need to show the data. Also, when you are using your own layout then R.java
should belong to your project not android.R
.
Change
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.list_content, items);
to
arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_content, R.id.textview, items);
回答2:
Issue is because of you are passing wrong type of argument.
After seeing your code I can say you want to use following version of ArrayAdapter.
public ArrayAdapter (Context context, int resource, int textViewResourceId, List<T> objects)
So following will work for you according to the code snippet provided by you.
arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_content, R.id.textview, items);
for different versions of arrayAdapter you can refer to : http://developer.android.com/reference/android/widget/ArrayAdapter.html
回答3:
What you are doing is declaring xml in your package and trying to access it from android.R.layout
package.
So, change
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.list_content, items);
to
arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_content, items);
It'll work
来源:https://stackoverflow.com/questions/35294627/arrayadapter-requires-the-resource-id-to-be-a-textview-issue