在不同的xml文件中更改TextView颜色

时间:2013-06-05 15:51:17

标签: android textview

我在一个xml中有一个ListView引用另一个xml中的T​​extView。我正在尝试更改TextView的颜色,但这似乎不起作用。如果我没有设置'setContentView'两次,我得到一个NullPointerException。

 setContentView(R.layout.text_list);
          TextView textView = (TextView) findViewById(R.id.logText);

          if (logLevel == "E"){
              textView.setTextColor(Color.parseColor("#FF4D4D"));
          }
          else if (logLevel == "W"){
              textView.setTextColor(Color.parseColor("#EAAB55"));
          }
          else if (logLevel == "I"){
              textView.setTextColor(Color.parseColor("#AFD778"));
          }
          else if (logLevel == "V"){
              textView.setTextColor(Color.parseColor("#OOOOOO"));
          }
          else {
              textView.setTextColor(Color.parseColor("#AFD778"));
          }

          setContentView(R.layout.log_cat);
          ListView lv1 = (ListView) findViewById(R.id.listView1);

          ArrayAdapter<String> arrayAdapter = 
                     new ArrayAdapter<String>(this, R.layout.text_list, log);

1 个答案:

答案 0 :(得分:1)

// setContentView(parm)两次可能会导致问题。因此,如果需要来自不同布局的视图,那么只需给它们充气

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.log_cat);
      ListView lv1 = (ListView) findViewById(R.id.listView1);

       CustomAdapter adapter = new CustomAdapter(this, "V");
           lv1 .setAdapter(adapter);
          adapter.notifyDataSetChanged();

}

//自定义适配器

   public class CustomAdapter extends BaseAdapter {

private Context ctx;
private String logLevel;

CustomAdapter (ArrayList<String> data, Context context, String log) 
{ 

     this.ctx = context;
     this.logLevel = log;
} 

@Override
public int getCount()  
{ 
    list.size();

} 

@Override
public Object getItem(int position)  
{ 
    return  null; 
} 

@Override
public long getItemId(int position)  
{ 
    return position ; 
} 

@Override
public View getView(int position, View convertView, ViewGroup parent)  
{ 
     LayoutInflater inflator = (LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
     View v = inflator.inflate(R.layout.text_list, null);

     TextView textView = (TextView) v.findViewById(R.id.logText);

     if (logLevel == "E"){
         textView.setTextColor(Color.parseColor("#FF4D4D"));
     }
     else if (logLevel == "W"){
         textView.setTextColor(Color.parseColor("#EAAB55"));
     }
     else if (logLevel == "I"){
         textView.setTextColor(Color.parseColor("#AFD778"));
     }
     else if (logLevel == "V"){
         textView.setTextColor(Color.parseColor("#OOOOOO"));
     }
     else {
         textView.setTextColor(Color.parseColor("#AFD778"));

         textView.setTextColor(Color.BLUE);
     }
     return textView;
   } 

}