我通过定义ArrayAdapter
的子类来创建自定义Listview
我的listview的每个项目都是XML
文件,其中包含两个textView。
它工作正常,但现在我想以编程方式更改列表的文本颜色。我尝试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_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="10dp" >
<TextView
android:id="@+id/textViewItemName"
android:layout_width="1dip"
android:layout_height="20dip"
android:text="TextView"
android:visibility="invisible"/>
<TextView
android:id="@+id/textViewItemContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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 ComponentInfo{vakili.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
mainActivity
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));
}
}
任何人都可以解释一种从自定义列表视图中更改textcolor的标准方法吗?
感谢。
答案 0 :(得分:0)
最后我找到了一个解决方案,不知道它的正常方式,但在这种情况下对我有用。我确实把settextcolor放在了ArrayAdapter Class的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;
}
}
非常感谢您的关注!