2016-07-06 7 views
1

Я создал пользовательский Listview, определяя подкласс ArrayAdapter . Каждый элемент моего списка представляет собой файл XML, содержащий два элемента textView. Это прекрасно работает, но теперь я хочу изменить цвет текста моего списка программно. Я попытался установить setTextColor() в текстовое окно, но приложение будет принудительно закрыто.Изменить цвет текста пользовательского ListView

** 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 от пользовательских ListView?

Спасибо.

+0

, пожалуйста, опубликуйте журнал ошибок –

+4

В вашем адаптере нет 'setTextColor()', также опубликуйте журнал ошибок. –

+0

Где вы устанавливаете цвет текста, помещаете весь код, а также помещаете журнал ошибок для своего приложения, закрываете – Vickyexpert

ответ

0

Наконец-то я нашел решение, не знаю его нормального пути, но в этом случае работал на меня. Я поместил settextcolor в orverriden метод класса 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); 
     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; 

    } 
} 

Действительно благодарю вас за беспокойство!

Смежные вопросы