Android listview:Items和SubItems中的不同颜色?

时间:2014-04-15 14:39:05

标签: android android-listview

是否可以将列表视图中的项目作为一种颜色,将其子项目作为不同的颜色?

我正在创建一个游戏(时间表测验游戏),其中用户提供的问题和答案以及正确的答案被转移到列表视图。 e.g:

项目 - " 7 x 5 =(用户回答)" subitem-"(正确答案)"

我想要问题,即" 7x5"如果不正确,则用户应答为绿色(如果正确)和红色(如果不正确)。并且正确答案始终是绿色

我想改变颜色的活动:

public class TestResults extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.testresults);

        ListView itemList = (ListView) findViewById(R.id.lvRandomTestresults);

        //gets all necessary data from the previous activity
        int[] results = getIntent().getIntArrayExtra("results");
        String[] questions= getIntent().getStringArrayExtra("Questions");
        int[] correctAnswer= getIntent().getIntArrayExtra("CorrectAnswer");

        ArrayList < HashMap <String, String> > list = new ArrayList < HashMap <String, String> > ();


        // loop to give list view
        for (int i = 1; i <= 10; ++i) {

            int userAnswer = results[i - 1];

            int expectedAnswer = correctAnswer[i-1];

            String userString = questions[i-1] + userAnswer;

            String expectedString = " " + expectedAnswer;

            HashMap<String, String> map = new HashMap<String, String>();

            map.put("user", userString);
            map.put("expected", expectedString);

            list.add(map);
        }

        String[] keys = {"user", "expected"};

        int[] ids = {android.R.id.text1, android.R.id.text2};

        SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, keys, ids);

        itemList.setAdapter(adapter);

    }//onCreate end 


}//class end 

与此活动对应的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="vertical" >

    <ListView 
       android:id="@+id/lvRandomTestresults"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" >

    </ListView>


</LinearLayout>

2 个答案:

答案 0 :(得分:1)

在您提供的代码中,您使用的是默认适配器,它根本不具备成本,您必须创建自己的adpater,所以让我们这样做:

首先,你必须在你的布局文件夹中添加一个xml文件,代表listView中的一行:

row.xml

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
            android:id="@+id/questionTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/answerTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</LinearLayout>

然后你必须创建你的costum Adapter,所以创建新的类并将其命名为 MyAdapter ,将此代码放入其中:

MyAdapter.java

public class MyAdapter extends ArrayAdapter<String> {

  private final Activity context;
  private final String[] questions;
  private final int[] answers;
  private final int[] rightAnswers;


  static class ViewHolder {
    public TextView text1;
    public TextView text2;
  }

  public MyAdapter(Activity context, String[] questions, int[] answers, int[] rightAnswers){
    super(context, R.layout.row, questions);

    this.context = context;
    this.questions= questions;
    this.answers= answers;
    this.rightAnswers= rightAnswers;
  }

 @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;

    if (rowView == null) {
      LayoutInflater inflater = context.getLayoutInflater();
      rowView = inflater.inflate(R.layout.row, null);

      // configure view holder
      ViewHolder viewHolder = new ViewHolder();
      viewHolder.text1 = (TextView) rowView.findViewById(R.id.questionTV);
      viewHolder.text2 = (TextView) rowView.findViewById(R.id.answerTV);

      rowView.setTag(viewHolder);
    }

    // fill data
    ViewHolder holder = (ViewHolder) rowView.getTag();

    String question = questions[position];
    int answer = answers[position];
    int rightAnswer = rightAnswers[position];

    //set Question in the text View with a BLACK backgroud color
    holder.text1.setText(question);
    //holder.text1.setBackgroundColor(Color.BLACK);

    //set User Answer with GREEN backgroun if it's correct or RED if it s not
    holder.text2.setText(String.valueOf(answer));
    if(answer == rightAnswer){
       holder.text2.setBackgroundColor(Color.GREEN);
    }else {
       holder.text2.setBackgroundColor(Color.RED);
    } 

    return rowView;
  }
}

最后,您需要使用以下内容自定义您的活动:

TestResults.java

public class TestResults extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.testresults);

        ListView itemList = (ListView) findViewById(R.id.lvRandomTestresults);

        //gets all necessary data from the previous activity
        int[] results = getIntent().getIntArrayExtra("results");
        String[] questions= getIntent().getStringArrayExtra("Questions");
        int[] correctAnswer= getIntent().getIntArrayExtra("CorrectAnswer");

        itemList.setAdapter(new MyAdapter(this, questions, results, correctAnswer));

    }//onCreate end 


}//class end 

如果需要,这是一个简单的测试:) enter image description here

答案 1 :(得分:0)

创建一个名为list_row.xml的新布局文件,作为列表行的布局。每行都有这个布局,每个布局都有两个TextView。

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/list_row.xml"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/questionLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/question"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:paddingLeft="10dp"
            android:paddingTop="2dp"
            android:paddingBottom="2dp"/>

        <TextView
            android:id="@+id/answer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:paddingLeft="10dp"
            android:paddingTop="2dp"
            android:paddingBottom="2dp"/>

    </LinearLayout>

    <TextView
        android:id="@+id/correct"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#00FF00"
        android:paddingLeft="10dp"
        android:paddingTop="2dp"
        android:paddingBottom="2dp"/>

</LinearLayout>

创建一个自定义ArrayAdapter来管理视图的颜色。将此类创建为内部类,或者如果需要,可以在单独的文件中创建。

MyArrayAdapter.java

public class MyArrayAdapter extends ArrayAdapter<ArrayList<HashMap<String, String>>>
{
    Context mContext;
    ArrayList<HashMap<String, String>> mQuestionArrayList;
    int mLayoutResourceId;
    String[] mQuestionsArray;
    int[] mUsersAnswers;

    public MyArrayAdapter(Context context, int layoutResourceId, ArrayList<HashMap<String, String>> questionsArrayList, String[] questionsArray, int[] usersAnswers)
    {
        super(context, layoutResourceId);
        mContext = context;
        this.mQuestionArrayList = questionsArrayList;
        this.mLayoutResourceId = layoutResourceId;
        this.mQuestionsArray = questionsArray;
        this.mUsersAnswers = usersAnswers;
    }

    @Override
    public int getCount()
    {
        return mQuestionArrayList.size();
    }

    @Override
    public View getView(int position, View row, ViewGroup parent)
    {
        HashMap<String, String> question = mQuestionArrayList.get(position);

        LayoutInflater inflater = LayoutInflater.from(mContext);

        // Here you will initialize the row layout, by inflating the xml file list_row.
        row = inflater.inflate(this.mLayoutResourceId, parent, false);

        // Here we initialize those two TextViews defined in the list_row layout.
        TextView questionTxtView = (TextView) row.findViewById(R.id.question);
        TextView answerTxtView = (TextView) row.findViewById(R.id.answer);
        TextView correctAnswerTxtView = (TextView) row.findViewById(R.id.correct);

        questionTxtView.setText(mQuestionsArray[position]);
        answerTxtView.setText(String.valueOf(mUsersAnswers[position]));
        correctAnswerTxtView.setText(question.get("expected").toString());

        // This is just a pseudo code to show you when and how to set the colors of
        // the TextView programatically.
        if(mUsersAnswers[position] != Integer.parseInt(question.get("expected").toString()))
            answerTxtView.setTextColor(Color.RED);
        else
            answerTxtView.setTextColor(Color.GREEN);

        return row;
    }
}

在您的Activity的onCreate()方法中,您应该有一个ListView对象,并以这种方式将您的自定义数组适配器(在上面作为示例定义)设置为ListView

你的onCreate()方法

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView itemList = (ListView) findViewById(R.id.lvRandomTestresults);

    //gets all necessary data from the previous activity
    int[] results = getIntent().getIntArrayExtra("results");
    String[] questions= getIntent().getStringArrayExtra("Questions");
    int[] correctAnswer= getIntent().getIntArrayExtra("CorrectAnswer");

    ArrayList< HashMap <String, String> > list = new ArrayList < HashMap <String, String> > ();

    // loop to give list view
    for (int i = 0; i < 10; i++) {

        int userAnswer = results[i];

        int expectedAnswer = correctAnswer[i];

        String userString = questions[i] + " " + userAnswer;

        String expectedString = "" + expectedAnswer;

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("user", userString);
        map.put("expected", expectedString);

        list.add(map);
    }

    // Instantiate your custom array adapter
    MyArrayAdapter adapter = new MyArrayAdapter(this.getApplicationContext(), R.layout.list_row, list, questions, results);

    // Here you set the custom adapter to your ListView.
    itemList.setAdapter(adapter);

}

我使用虚构值测试了代码,下面的结果是从此答案中编写的代码中检索的。 enter image description here


如果您有更多疑问,请与我们联系。

希望这能帮到你!