无法在 Android 中设置 ListView Divider 颜色

Unable to set ListView Divider color in Android

我有一个 activity,里面有一个 ListView。我已使用 android:divider="#000000" 属性将 ListView 分隔线的颜色设置为黑色,并将分隔线高度设置为 1dp。由于某种原因,分隔线显示为蓝色而不是黑色。这是我的 xml。任何帮助将不胜感激。

second_selection.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1A1A1A"
    android:orientation="vertical"
    tools:context="com.example.saregama.MainActivity" >

    <FrameLayout
        android:id="@+id/myframe"
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:background="#000000" />

    <include
        android:id="@+id/new_tool"
        layout="@layout/toolbar_actionbar_with_headerbar" />

    <ImageView
        android:id="@+id/loader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:src="@drawable/newloading" />

    <ListView
        android:id="@+id/product_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#000000"
        android:dividerHeight="1dp"
        android:layoutAnimation="@anim/layout_bottom_to_top_slide"
        android:padding="10dp"
        android:text="@string/hello_world" />

</LinearLayout>

如有必要,这是我的代码

SecondSelection.java

package com.example.something;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class SecondSelection extends ActionBarActivity {
    Activity context;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    ProgressDialog pd;
    CustomAdapter adapter;
    ListView listProduct;
    ArrayList<String> records;
    Intent i;
    Intent j;
    Intent k;
    private Toolbar toolbar;
    ValueAnimator colorAnimation;
    FrameLayout myframe;
    ValueAnimator statusAnim;
    ImageView image;
    Animation anim;
    BackTask bt;

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_selection);
        toolbar = (Toolbar) findViewById(R.id.new_tool);
        setSupportActionBar(toolbar);
        myframe = (FrameLayout)findViewById(R.id.myframe);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow(); // in Activity's onCreate() for instance
            w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        else{
            myframe.setVisibility(View.GONE);

        }
        context = this;
        records = new ArrayList<String>();
        listProduct = (ListView) findViewById(R.id.product_list);
        image = (ImageView)findViewById(R.id.loader);
        anim = AnimationUtils.loadAnimation(this, R.anim.myanim);
        image.startAnimation(anim);
        i = new Intent(this, ReportActivity.class);
        j = new Intent(this, RequestActivity.class);
        k = new Intent(this, AboutDeveloper.class);
        bt = new BackTask();
        bt.execute();
        adapter = new CustomAdapter(context, R.layout.list_item_second,
                R.id.pro_name, records);
        listProduct.setAdapter(adapter);
        listProduct.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position,
                    long id) {

                String sText = ((TextView) v.findViewById(R.id.pro_name))
                        .getText().toString();
                Intent songIntent = new Intent(getApplicationContext(),
                        MainActivity.class);
                songIntent.putExtra("second_selection", sText);
                startActivity(songIntent);

            }

        });

        //Animation for Action Bar

           Integer colorFrom = getResources().getColor(R.color.first);
           Integer colorTo = getResources().getColor(R.color.last);
           colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
           colorAnimation.addUpdateListener(new AnimatorUpdateListener() {

               @Override
               public void onAnimationUpdate(ValueAnimator animator) {
                   toolbar.setBackgroundColor((Integer)animator.getAnimatedValue());
               }

           });


           //Animation for Status Bar

           Integer colorFirst = getResources().getColor(R.color.begin);
           Integer colorLast = getResources().getColor(R.color.end);
           statusAnim = ValueAnimator.ofObject(new ArgbEvaluator(), colorFirst, colorLast);
           statusAnim.addUpdateListener(new AnimatorUpdateListener() {

               @Override
               public void onAnimationUpdate(ValueAnimator animator) {
                   myframe.setBackgroundColor((Integer)animator.getAnimatedValue());
               }

           });

           //Start the Animations after fetching the list.
           //After executing the bt.execute()
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onStart()
    {
        super.onStart();
        if (bt.getStatus() == Status.FINISHED) {
            doAnimation();
        }
    }

    private void doAnimation() {
         statusAnim.setDuration(800);
            colorAnimation.setDuration(1300);
            colorAnimation.start();
            statusAnim.start();     // start animations
        }

    // background process to make a request to server and list product
    // information
    private class BackTask extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute() {
            super.onPreExecute();
        //  pd = new ProgressDialog(context);
        //  pd.setTitle("Retrieving data");
        //  pd.setMessage("Please wait.");
        //  pd.setCancelable(true);
        //  pd.setIndeterminate(true);
        //  pd.show();

        }

        protected Void doInBackground(Void... params) {

            InputStream is = null;
            String result = "";
            try {

                records.clear();

                httpclient = new DefaultHttpClient();
                httppost = new HttpPost(
                        "");
                response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {

                if (pd != null)
                    pd.dismiss(); // close the dialog if error occurs
                Log.e("ERROR", e.getMessage());

            }

            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "utf-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("ERROR", "Error converting result " + e.toString());

            }

            // parse json data
            try {

                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    String record = json_data.getString("alp") + "__"
                            + json_data.getString("f");
                    records.add(record);

                }

            } catch (Exception e) {
                Log.e("ERROR", "Error pasting data " + e.toString());

            }

            return null;
        }

        protected void onPostExecute(Void result) {

        //  if (pd != null)
        //      pd.dismiss(); // close dialog
            image.clearAnimation();
            image.setVisibility(View.GONE);
            adapter.notifyDataSetChanged();
            doAnimation();// notify the ListView to get new
                                            // records

        }

    }
}

更新:

只有 API < 19

的设备才会出现此问题

使用android:background代替android:divider

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1A1A1A"
android:orientation="vertical"
tools:context="com.example.saregama.MainActivity" >

<FrameLayout
    android:id="@+id/myframe"
    android:layout_width="match_parent"
    android:layout_height="25dp"
    android:background="#000000" />

<include
    android:id="@+id/new_tool"
    layout="@layout/toolbar_actionbar_with_headerbar" />

<ImageView
    android:id="@+id/loader"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:src="@drawable/newloading" />

<ListView
    android:id="@+id/product_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:divider="#000000"
    android:dividerHeight="1dp"
    android:layoutAnimation="@anim/layout_bottom_to_top_slide"
    android:padding="10dp"
    android:text="@string/hello_world" />

我在 styles.xml:

中为 ListViews 设置了样式
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    ...
    <style name="ListViews" parent="@android:style/Widget.ListView">
        <item name="android:cacheColorHint">@color/transparent</item>
        <item name="android:divider">@drawable/list_divider</item>
        <item name="android:dividerHeight">1px</item>
    </style>
    ...
</resources>

我的 ListView 就这样使用了那个样式:

style="@style/ListViews"

显然,我的 drawable 文件夹中有这样的 drawable。
我的 list_divider.xml 可绘制对象是这样的:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <solid android:color="@color/navy_semi" />
</shape>

[编辑]

显然,不要使用 @color/transparent@color/navy_semi,而是使用您自己的颜色。
这些仅在 my 颜色资源中定义。

在您的列表视图中使用以下属性。

android:cacheColorHint="@null" 

如果没有任何效果,那么您可以创建自己的分隔线。

首先删除默认分隔符。

android:dividerHeight="0dp" android:divider="@null"

然后在您的 custom_row_layout.xml 中添加视图 `

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="30dp"
        android:paddingTop="8dp"
        android:paddingBottom="8dp"
        android:textSize="17sp"
        android:textColor="@color/white" />

     <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/white" />
</LinearLayout>

`