刚开始,ListView用Android自带的simple_list_item_1显示简单文本。使用默认属性,代码如下:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, adapterData);
listView.setAdapter(adapter);
之后,功能更新时需要更改item字体颜色及规定typeface,res/layout/文件夹下自定义了record_text.xml文件:
<?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="match_parent"> <TextView android:id="@+id/TView" android:layout_width="match_parent" android:layout_height="match_parent" android:textColor="#2d373c" android:textSize="18sp" /> </LinearLayout>
将.java文件中代码改为:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(RecordActivity.this, R.layout.record_text, adapterData); listView.setAdapter(adapter); //把item显示文本改为自定义字体 LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.record_text, null); TextView w = (TextView)view.findViewById(R.id.TView); Typeface tfsisan03 = Typeface.createFromAsset(getAssets(), "fonts/sisan03_0.ttf"); w.setTypeface(tfsisan03);
运行,错误提示:ArrayAdapter requires the resource ID to be a TextView。最后发现是.xml文件的问题。根标签必须是TextView,不能嵌套LinearLayout等,修改之后,错误解决。
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/TView"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#2d373c"
android:layout_marginLeft="10dp"
android:paddingLeft="10dp"
android:gravity="center_vertical"
android:textSize="16sp"
/>