我正在尝试动态地将textview添加到listview。在添加im设置文本之前,但在listview文本中看起来像'android.widget.TextView@45f ...'
private ArrayAdapter<TextView> dizi;
private ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listview);
dizi = new ArrayAdapter<TextView>(this, R.layout.asd);
list.setAdapter(dizi);
TextView qwe = new TextView(getApplicationContext());
qwe.setText("txt");
dizi.add(qwe);
}
asd布局文件:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:padding="5dp"
/>
我尝试在asd布局文件中使用linearlayout更改textview元素,但它没有用。
我无法弄明白。我该怎么做?
谢谢..
答案 0 :(得分:3)
这是因为ArrayAdapter
正常实现了它所持有的对象toString()
,因此可以确保它们可以显示。
由于ArrayAdapter
已经使用TextView
来显示数据,我建议您更改适配器,使其为ArrayAdapter<String>
,然后只需添加要显示的字符串。< / p>
dizi = new ArrayAdapter<String>(this, R.layout.asd);
list.setAdapter(dizi);
dizi.add("txt");
dizi.notifyDataSetChanged();
如果要更改布局,请展开ArrayAdapter
并覆盖getView()
方法。这个tutorial进一步深入。
由ArrayAdapter
List
个String
支持Spannable
实施某些public class ExampleAdapter extends ArrayAdapter<String> {
LayoutInflater inflater;
int resId;
int layoutId;
public ExampleAdapter(Context context,int layoutId, int textViewResourceId,
List<String> objects) {
super(context, layoutId, textViewResourceId, objects);
this.inflater = LayoutInflater.from(context);
this.layoutId = layoutId;
this.resId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
convertView = inflater.inflate(layoutId, parent,false);
String text = getItem(position);
Spannable s = Spannable.Factory.getInstance().newSpannable(text);
s.setSpan(new ForegroundColorSpan(Color.RED), 0, text.length()/2, 0);
s.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, text.length()/2, 0);
s.setSpan(new ForegroundColorSpan(Color.DKGRAY), text.length()/2, text.length(), 0);
s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), text.length()/2, text.length(), 0);
((TextView)convertView.findViewById(resId)).setText(s, TextView.BufferType.SPANNABLE);
return convertView;
}
}
s的小例子:
ArrayList <String> items = new ArrayList <String> ();
items.add ("Array Adapter");
ExampleAdapter dizi = new ExampleAdapter (YourActivity.this,android.R.layout.simple_list_item_1,android.R.id.text1,items);
list.setAdapter(dizi);
dizi.add ("your text");
dizi.notifyDataSetChanged();
结果:
要创建它的一个实例(假设你是从一个Activity那里做的),我做了什么:
{{1}}