1

我正在开发我的第一个 Android 应用程序,在阅读了这里已经发布的许多答案之后,他们提高了我的理解,但似乎无法解决我的问题。

简而言之,我有一个ListView并且我希望某些行中的文本与其他行不同。我试图通过将 a 转换ListView.GetItemAtPosition为 aTextView并更改其文本颜色来做到这一点,但我遇到了一个转换异常。

非常感谢帮助我找出代码中的错误或提出更好的方法!

public class MeetingManager extends Activity {

public ListView mAgenda;

//public Item agenda = new Item();
List<Item> agenda=new ArrayList<Item>();
ArrayAdapter<Item> adapter=null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.meeting);

    // Obtain handles to UI objects
    mAgenda = (ListView)findViewById(R.id.lstAgenda);

    adapter=new ArrayAdapter<Item>(this, R.layout.agendalist, agenda);
    mAgenda.setAdapter(adapter);        
    mAgenda.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    //Load items into agenda
    initAgenda();
}

protected void updateDetails() {
    mRecipients.setText("This message will be sent to items " + (currentItemNum + 1) + " and later:");
    mSMS.setText(currentItem.getSMS());
}

protected void initAgenda() {
    currentItem = new Item();
    currentItem.setTitle("Reset Meeting");
    adapter.add(currentItem);
    setColour(0, Color.RED);
}

public void setColour(int pos, int col) {
    TextView tv = (TextView)mAgenda.getItemAtPosition(pos); //This is where the exception is thrown
    tv.setTextColor(col);
}
}

以下是我的 XML 代码ListView

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1"  
    android:paddingTop="2dip" 
    android:paddingBottom="3dip"
    android:textSize="12pt" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" /> 
4

2 回答 2

2

您需要创建一个自定义适配器并根据您的着色标准TextView.setTextColor();在该方法中使用。getView

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null)
        convertView = View.inflate(context, layout, null);
    View row = convertView;

    TextView first = (TextView) convertView.findViewById(R.id.ListItem1);
    TextView second = (TextView) convertView.findViewById(R.id.ListItem2);
    if(condition == changecolor) {
        first.setTextColor(#FFFF0000);
        second.setTextColor(#FFFF0000);
    }
}
于 2012-06-16T06:25:27.810 回答
0

您可以子类ArrayAdapter化并在子类的 getView 方法中,您可以执行魔术

public View getView(int position, View convertView, ViewGroup parent) {
  TextView tv = super.getView(position, convertView, parent);

  if (position < 3) {     // I have just put dummy condition you can put your condition
    textView.setTextColor(colors);  // Here you can put your color
  } else {
    textView.setTextColor(colors);
  }
}
于 2012-06-16T06:29:02.680 回答