在这个网站上搜索任何答案,我找不到真正简单的解决方案。我正在创建一个Android应用程序,它使用sqlite数据库通过输入的颜色名称查找十六进制值。我动态创建TextView,设置其文本和文本颜色,然后将其添加到ArrayList,然后ArrayList正在添加到ListView。文本显示在ListView中,但其颜色属性未设置。我真的想找到一种方法来获取每个listview项的文本颜色集。这是我到目前为止的代码:
类变量:
private ListView lsvHexList;
private ArrayList<String> hexList;
private ArrayAdapter adp;
在onCreate()中:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color2hex);
lsvHexList = (ListView) findViewById(R.id.lsvHexList);
hexList = new ArrayList<String>();
在我的按钮处理程序中:
public void btnGetHexValueHandler(View view) {
// Open a connection to the database
db.openDatabase();
// Setup a string for the color name
String colorNameText = editTextColorName.getText().toString();
// Get all records
Cursor c = db.getAllColors();
c.moveToFirst(); // move to the first position of the results
// Cursor 'c' now contains all the hex values
while(c.isAfterLast() == false) {
// Check database if color name matches any records
if(c.getString(1).contains(colorNameText)) {
// Convert hex value to string
String hexValue = c.getString(0);
String colorName = c.getString(1);
// Create a new textview for the hex value
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText());
} // end if
// Move to the next result
c.moveToNext();
} // End while
adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexList);
lsvHexList.setAdapter(adp);
db.close(); // close the connection
}
答案 0 :(得分:3)
您根本没有将创建的TextView添加到列表中,只需将String添加到列表中,因此您在TextView上调用的方法无关紧要:
if(c.getString(1).contains(colorNameText)) {
// ...
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText()); // apend only the text to the list
// !!!!!!!!!!!!!! lost the TextView !!!!!!!!!!!!!!!!
}
您需要做的是将颜色存储在另一个数组中,并在创建实际列表视图时,根据列表中的相应值设置每个TextView的颜色。
为此,您需要扩展ArrayAdapter
并在其中添加TextView颜色的逻辑。