更改自定义 ListView 的 textcolor
Posted
技术标签:
【中文标题】更改自定义 ListView 的 textcolor【英文标题】:Change textcolor of a custom ListView 【发布时间】:2016-11-08 07:27:24 【问题描述】:我通过定义ArrayAdapter
的子类创建了一个自定义列表视图
我的列表视图的每一项都是一个XML
文件,其中包含两个文本视图。
它工作正常,但现在我想以编程方式更改列表的文本颜色。我试图 setTextColor()
到 textView 的,但应用程序会强制关闭!。
** textfile_item_row.XML :显示每个列表视图项**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="horizontal"
android:padding="10dp" >
<TextView
android:id="@+id/textViewItemName"
android:layout_
android:layout_
android:text="TextView"
android:visibility="invisible"/>
<TextView
android:id="@+id/textViewItemContent"
android:layout_
android:layout_
android:text="TextView"
android:textColor="#ffffff"
android:textColorHighlight="#000000"
android:typeface="monospace"/>
</LinearLayout>
public class TextFile
public String name;
public String content;
public TextFile()
super();
public TextFile(String name, String content)
super();
this.name = name;
this.content = content;
这是我的自定义 ArrayAdapter
public class TextFileAdapter extends ArrayAdapter<TextFile>
Context context;
int layoutResourceId;
ArrayList<TextFile> data = null;
public TextFileAdapter(Context context, int layoutResourceId, ArrayList<TextFile> data)
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
@Override
public View getView(int position, View convertView, ViewGroup parent)
View row = convertView;
TextFileHolder holder = null;
if (row == null)
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new TextFileHolder();
holder.txtName = (TextView) row.findViewById(R.id.textViewItemName);
holder.txtContent = (TextView) row.findViewById(R.id.textViewItemContent);
row.setTag(holder);
else
holder = (TextFileHolder) row.getTag();
TextFile textFile = data.get(position);
holder.txtContent.setText(textFile.content);
holder.txtName.setText(textFile.name);
return row;
static class TextFileHolder
TextView txtName;
TextView txtContent;
在我的主要活动中
ArrayList<TextFile> textData = new ArrayList<TextFile>();
。 . . .
TextFileAdapter adapter = new TextFileAdapter(this,R.layout.textfile_item_row, textData);
listView1.setAdapter(adapter);
我的日志猫:
07-06 20:12:47.996: E/AndroidRuntime(652): FATAL EXCEPTION: main
07-06 20:12:47.996: E/AndroidRuntime(652): java.lang.RuntimeException: Unable to start activity ComponentInfovakili.ramin.apps.actionbartest/vakili.ramin.apps.actionbartest .MainActivity: java.lang.NullPointerException
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.ActivityThread.access$600(ActivityThread.java:123)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.os.Handler.dispatchMessage(Handler.java:99)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.os.Looper.loop(Looper.java:137)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-06 20:12:47.996: E/AndroidRuntime(652): at java.lang.reflect.Method.invokeNative(Native Method)
07-06 20:12:47.996: E/AndroidRuntime(652): at java.lang.reflect.Method.invoke(Method.java:511)
07-06 20:12:47.996: E/AndroidRuntime(652): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:78 4)
07-06 20:12:47.996: E/AndroidRuntime(652): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-06 20:12:47.996: E/AndroidRuntime(652): at dalvik.system.NativeStart.main(Native Method)
07-06 20:12:47.996: E/AndroidRuntime(652): Caused by: java.lang.NullPointerException
07-06 20:12:47.996: E/AndroidRuntime(652): at vakili.ramin.apps.actionbartest.MainActivity.showUserSettings(MainActivity.java:235)
07-06 20:12:47.996: E/AndroidRuntime(652): at vakili.ramin.apps.actionbartest.MainActivity.onCreate(MainActivity.java:43)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.Activity.performCreate(Activity.java:4465)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-06 20:12:47.996: E/AndroidRuntime(652): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
07-06 20:12:47.996: E/AndroidRuntime(652): ... 11 more
主活动
public class MainActivity extends Activity
ListView listView1;
private static final int RESULT_OK = 1;
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getOverflowMenu();
listView1 = (ListView) findViewById(R.id.listView1);
readTextFiles();
showUserSettings();
listView1.setOnItemClickListener(new OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
TextView textView1 = (TextView) view.findViewById(R.id.textViewItemName);
String itemName = textView1.getText().toString();
File STR = new File(Environment.getExternalStorageDirectory().toString() + "/testfiles");//sdcard directory->/mnt/sdcard
File myText = new File(STR + "/" + itemName);
StringBuilder txtContent = new StringBuilder();
try
BufferedReader br = new BufferedReader(new FileReader(myText));
String line;
while ((line = br.readLine()) != null)
txtContent.append(line);
txtContent.append('\n');
br.close();
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("txtName", itemName); //pass the file name and content to the second activity
i.putExtra("txtContent", txtContent.toString());//remember we added our second activity in manifest
startActivityForResult(i, 1);
catch (IOException e)
);
@Override
public boolean onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
@Override
public boolean onOptionsItemSelected(MenuItem item)
super.onOptionsItemSelected(item);
switch (item.getItemId())
case R.id.add_activity1:
Intent i = new Intent(MainActivity.this, ThirdActivity.class);
startActivityForResult(i, RESULT_OK);
break;
case R.id.setting_activity1:
Intent i2 = new Intent(this, SettingActivity.class);
startActivityForResult(i2, RESULT_OK);
break;
case R.id.about_activity1:
Toast.makeText(getApplicationContext(), "Coming soon ... :) ", Toast.LENGTH_SHORT).show();
break;
return true;
private void getOverflowMenu()
try
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null)
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
catch (Exception e)
e.printStackTrace();
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
case RESULT_OK:
showUserSettings();
break;
finish();
startActivity(getIntent());
public void readTextFiles()
ArrayList<TextFile> textData = new ArrayList<TextFile>();
Log.i("11111", "*********");
File STR = new File(Environment.getExternalStorageDirectory().toString() + "/testfiles");//sdcard directory->/mnt/sdcard
if ( !STR.exists())
STR.mkdir();
File myFolder = new File(STR.toString());
//*****************************************
File fileDir;
StringBuilder txtContent = new StringBuilder();
String txtName;
BufferedReader br;
String line;
TextFile tempFile = new TextFile();
Log.i("22222", "*********");
File[] myFiles = myFolder.listFiles();
//*******************************************
for (int i = 0; i < myFiles.length; i++)
File file = myFiles[i];
if (file.isFile() && file.getName().endsWith(".txt"))
txtName = file.getName().toString();
fileDir = new File(STR + "/" + txtName);//reading the file contnt
try
br = new BufferedReader(new FileReader(fileDir));
while ((line = br.readLine()) != null)
txtContent.append(line);
txtContent.append('\n');
tempFile = new TextFile(txtName, txtContent.toString());
textData.add(tempFile);
txtContent.delete(0, txtContent.length());//deleteing txtContent
br.close();
catch (Exception e)
TextFileAdapter adapter = new TextFileAdapter(this, R.layout.textfile_item_row, textData);
listView1.setAdapter(adapter);
private void showUserSettings()
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
String backgroundColor = sharedPrefs.getString("backgroundColor", "#14a584");
listView1.setBackgroundColor(Color.parseColor(backgroundColor));
任何人都可以解释从自定义列表视图中更改文本颜色的标准方法吗?
谢谢。
【问题讨论】:
请发布错误日志 您的适配器中没有setTextColor()
,请同时发布错误日志。
你在哪里设置文本颜色,放置整个代码,并关闭你的应用程序的错误日志
请从 'MainActivity.java:235' 发布 sn-p 代码
What is a NullPointerException, and how do I fix it?的可能重复
【参考方案1】:
最后我找到了一个解决方案,不知道它的正常方式,但在这种情况下对我有用。我确实将 settextcolor 放在了 ArrayAdapter 类的 orverriden 方法中。
public class TextFileAdapter extends ArrayAdapter<TextFile>
Context context;
int layoutResourceId;
ArrayList<TextFile> data = null;
public TextFileAdapter(Context context, int layoutResourceId, ArrayList<TextFile> data)
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
@Override
public View getView(int position, View convertView, ViewGroup parent)
View row = convertView;
TextFileHolder holder = null;
if (row == null)
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new TextFileHolder();
holder.txtName = (TextView) row.findViewById(R.id.textViewItemName);
holder.txtContent = (TextView) row.findViewById(R.id.textViewItemContent);
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
String textColor = sharedPrefs.getString("textColor", "#000000");
holder.txtContent.setTextColor(Color.parseColor(textColor));
row.setTag(holder);
else
holder = (TextFileHolder) row.getTag();
TextFile textFile = data.get(position);
holder.txtContent.setText(textFile.content);
holder.txtName.setText(textFile.name);
return row;
static class TextFileHolder
TextView txtName;
TextView txtContent;
非常感谢您的关心!
【讨论】:
以上是关于更改自定义 ListView 的 textcolor的主要内容,如果未能解决你的问题,请参考以下文章
Android - ListView 中的 EditTexts 绑定到自定义 ArrayAdapter - 跟踪更改
使用自定义适配器更改ListView中特定行中的ImageView
如何使用edittexts在自定义ListView中实现监听器文本更改?
在自定义适配器类中发送服务器请求后,如何更改 Listview 按钮名称?