如何根据每行中的内容更改ListView中行的颜色?

时间:2017-05-05 20:13:14

标签: java android arrays listview android-arrayadapter

我在Android的SolutionActivity类中有一个listview。适配器根据另一个活动中用户输入的结果填充列表中的元素。列表视图只能有两个值," true"或者错误"。我在网上搜索过,我看到很多“getView'在自定义适配器类中调用的方法然而我试图实现这个但我无法弄清楚如何?我是否只为我的适配器创建了一个单独的类?或者我可以在SolutionActivity的末尾添加它吗?我如何使用getView方法?无论如何这是我的代码...

public void setUserResults() { //displays the bit combination and users services in the listviews
    ListView serviceNames = (ListView) findViewById(R.id.listofservices);
    ListView bitResults = (ListView) findViewById(R.id.bitresults);
    UserInputSet userInputSet = UserInputSet.getInstance();
    List<String> userServices = MainActivity.dimensions;
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            userServices);
    ArrayAdapter<Boolean> bitArrayAdapter = new ArrayAdapter<Boolean>(this, android.R.layout.simple_list_item_1,
            CustomUseCase.getBestComboArray());
    serviceNames.setAdapter(arrayAdapter);
    bitResults.setAdapter(bitArrayAdapter);
}

如果&#39; getBestComboArray()&#39;的值,我想将行设置为绿色。是的,如果是假的,则为红色。任何人都可以建议一个很好的解决方案?谢谢

1 个答案:

答案 0 :(得分:2)

创建自定义适配器类

public class CustomAdapter extends ArrayAdapter<String> {
private List<Boolean> greenColor;
private List<String> Words;

public CustomAdapter(Activity context, List<String> words,List<Boolean> layoutcolor)
{
                   Words = words; 
            this.context = context
            greenColor = layoutcolor;

}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    if(view==null)
        view = LayoutInflater.from(getContext()).inflate(R.layout.list_item,parent,false);


    View view1 = view.findViewById(R.id.colorContainer);

    if(layoutColor.get(position)){
    view1.setBackgroundColor(Color.GREEN);
     }else{
            view1.setBackgroundColor(Color.RED);
          }


    TextView textViewdefault = (TextView)    view.findViewById(R.id.text_view);
    textViewdefault.setText(words.get(position));

    return view;

}
}

使用名称list_item创建布局,并使用您想要在每行显示的视图进行更改

    <LinearLayout
    android:id="@+id/colorContainer"
    android:layout_width="match_parent"
    android:layout_toRightOf="@id/image"
    android:layout_height="match_parent"
    android:orientation="vertical"

    >
<TextView
    android:id="@+id/text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="text1"
    android:textSize="18sp"
    android:paddingTop="16dp"
    android:layout_marginLeft="16dp"
    android:textColor="#ffffff"
    />



</LinearLayout>

然后设置调用适配器列表视图

CustomAdapter <String> bitArrayAdapter = new CustomAdapter <String>(this,  TextViewList, // TextViewList is the list of text for textview of each row
CustomUseCase.getBestComboArray());

bitResults.setAdapter(bitArrayAdapter);

你很高兴:)