如何在 Sqlite 数据库中的特定数据上更改 Listview 中的行颜色

Posted

技术标签:

【中文标题】如何在 Sqlite 数据库中的特定数据上更改 Listview 中的行颜色【英文标题】:How to change the rows color in Listview on specific data from Sqlite database 【发布时间】:2019-10-18 18:58:09 【问题描述】:

我有自定义列表视图,我的数据来自 sqlite 数据库。现在我想根据 id 更改特定列表视图项的背景颜色。首先,我检查数据库中是否存在 id,然后根据 id 更改特定项目行的背景颜色。

我的问题是它检查成功,但是当我尝试更改背景颜色时,它会更改整个列表视图的背景颜色。这是我的数据的图片和代码。那你就会明白我的意思了,我到底想说什么!

我的数据库:

整个listview颜色变化:

我的代码:

package bible.swordof.God;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;


import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;

import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;

public class FullverseAdopter extends ArrayAdapter<String> 
    private ALLVERSE activity;

    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private boolean highlight=false;
    LinearLayout linearLayout;


public  String ex="switch";

    //check for availabe language
    int result;


    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) 
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;



    


    @Override
    public int getCount() 
        return versenumber.size();
    

    @Override
    public String getItem(int position) 
        return versenumber.get(position);
    

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

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) 
        final ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) 
            // inflate UI from XML file
             convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
           holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
            holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);

//check if id is exits in db
            if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))
            

                holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));
            



            convertView.setTag(holder);
         else 
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        
        holder.versenumber.setText(versenumber.get(position));

        holder.verselist.setText(verselist.get(position));





holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() 




    @Override
    public boolean onLongClick(View v) 

        //Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
        Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
        vibe.vibrate(100);


        Toast.makeText(activity, ""+verseid.get(position), Toast.LENGTH_SHORT).show();







      /*  ColorPicker colorPicker = new ColorPicker(activity);
        ArrayList<String>colors=new ArrayList<>();
        colors.add("#e0e0eb");
        colors.add("#ccffff");
        colors.add("#ffe6ff");
        colors.add("#ffffcc");
        colors.add("#ccffcc");
        colors.add("#e6f2ff");
        colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() 
            @Override
            public void onChooseColor(int position, int color) 





              //  holder.linearLayout.setBackgroundColor(color);





            

            @Override
            public void onCancel() 

            
        ).show();*/






        return false;
    
);
        /*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() 
            @Override
            public boolean onLongClick(View v) 
                holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
                return false;
            
        );*/

//verselist highlight

/*holder.verselist.setOnClickListener(new View.OnClickListener() 
    @Override
    public void onClick(View v) 






    
);*/



        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);

            
        );

//add in favourite
      holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() 

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 

                if(isChecked)
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    ContentValues contentValues=new ContentValues();
                  contentValues.put("id",verseid.get(position));
                  contentValues.put("bookname",refernce.get(position));
                   contentValues.put("versenumber",versenumber.get(position));
                   contentValues.put("verse",verselist.get(position));
                   long check=mDb.insert("favourite",null,contentValues);
                   Log.d("MY_TAG","DB IS NOW "+check);
                   Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();


                else 


                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    long delete= mDb.delete("favourite","id=?",new String[]verseid.get(position));
                   Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
                


            
        );

       /* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() 
            @Override
            public void onInit(int status) 

                if (status == TextToSpeech.SUCCESS) 
                    result = textToSpeech.setLanguage(Locale.ENGLISH);
                 else 

                    Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                
            
        );
*/



        //My toggle button








       /* holder.speakverse.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 

                Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) 

                    Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                 else 


                    textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);

                
            
        );*/




        return convertView;
    

    static class ViewHolder 
        private TextView versenumber;
        private TextView verselist;

        private ImageView share;
        private  ToggleButton addfavoruite;
        private ImageView speakverse;
        private LinearLayout linearLayout;

        public ViewHolder(View v) 
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
           share = (ImageView) v.findViewById(R.id.share);
            /*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
        addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
        linearLayout=(LinearLayout)v.findViewById(R.id.layout);



        


    
    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) 

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0)
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        else 


            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();

        
        cursor.close();


        return true;
    
    public  void opecolorpicker()

    


【问题讨论】:

if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001")) 你需要else - 更改为默认值,并将其移出if (convertView == null) @VladyslavMatviienko 相同的输出 好的,我明白了。您的条件是恒定的,这意味着对每一行检查CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"),并且对于每一行都是相同的。您不检查任何特定于行的内容 那么我如何检查具体的? @VladyslavMatviienko 请告诉我? 【参考方案1】:

假设您将ID存储在private List&lt;String&gt;verseid;中,您可以使用它来检查当前ListView项目的ID。 当前项目位置在final int position 参数中传递给您。 所以要检查和应用颜色: 删除

if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))

     holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));

来自if (convertView == null) 然后在 if 之外添加此代码:

if("1001001".equals(verseid.get(position))) 
    //change the color
 else 
    //set the color to default

请注意,由于ListView 的工作方式(回收物品),您必须在else 中设置默认颜色。

【讨论】:

以上是关于如何在 Sqlite 数据库中的特定数据上更改 Listview 中的行颜色的主要内容,如果未能解决你的问题,请参考以下文章

如果光标具有特定值,则更改 ListView 中的图像

在 iPhone 上更新 SQLite 数据库

当sqlite android片段中的数据更改或删除时如何刷新recyclerview?

如何使用 sqlite 中的视图在特定行中添加列?

如何从 SQLite 数据库中的用户位置检索特定范围内的一组位置

如何在ios中更改特定单元格图像相对于索引路径?