Android:listview无法以编程方式突出显示所选行

时间:2015-08-11 12:24:52

标签: android listview

我正在尝试以编程方式突出显示列表视图中的所选行。 我有一个简单的测验应用程序,有前一个和下一个按钮。一旦用户选择了一个选项,它就会突出显示,并在按下sqllite数据库中的下一个按钮时保存,并显示一个新问题。 点击上一个按钮,我可以显示上一个问题,并且我能够获得他为该特定问题选择的位置。

问题

我试图以编程方式突出显示所选选项。

注意

如果您不想阅读整个代码,请查看PrevQuestion()函数

我的代码

public class Aptitude extends Activity implements OnClickListener {

    DBHelper helper;
    SQLiteDatabase db;
    Button btnBegin,btnnext,btnredirect,btnPrev;
    int count = 0;
    int response = 0;
    int Submodules;
    int iQuestionNo;
    int StudentID = 0;
    TextView tvQuestionNoAptitude ,tvTimer, tvOptiontitle;
    View previouslySelectedItem = null;
    CounterClass timer;


    //Sub category Buttons
    Button btnaptitude5,btnaptitude4,btnaptitude3,btnaptitude2,btnaptitude1,btnSubmitTest;

    String QuestionNo,Title,TitleDescription,QuestionText,QuestionTemplate,QuestionImage,Submodule , QuestionID, stroptiontitle,strOptionResponseID,strStudentIDfromPrevPage ,strselected_StudentID;

    //String SubModuleQuestion_ID;

    TextView tvTitle,tvInstructions,tvQuestionText;

    RadioGroup rgtemplate4images;
    ImageView img;
     RelativeLayout aptitudesubcateg,temp5optimage, redirecttemplate;
    ListView listviewoptions;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.aptitude);

          temp5optimage = (RelativeLayout) findViewById(R.id.temp5optimage);

          temp5optimage.setClickable(false);

          redirecttemplate = (RelativeLayout) findViewById(R.id.redirecttemplateaptitude);

         // int position = 1;
          listviewoptions = (ListView)findViewById(R.id.lstviewoptionAptitude);

            listviewoptions.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,int position ,
                        long arg3) {

                    //arg1.setBackgroundColor(getResources().getColor(
                               // R.color.pressed_color)); 

                     if (previouslySelectedItem != null)
                        {
                            previouslySelectedItem.setBackgroundColor(Color.TRANSPARENT);
                                    //getResources().getColor(R.color.pressed_color));
                        }

                     String Selectedcolor = "#fdc500";
                     arg1.setBackgroundColor(Color.parseColor(Selectedcolor));
                               // getResources().getColor(R.color.default_color));

                        previouslySelectedItem = arg1;
                    // TODO Auto-generated method stub
                //   Toast.makeText(getApplicationContext(),String.valueOf(response), Toast. LENGTH_SHORT).show();
                     response = position+1;
                }
            });


         temp5optimage.setVisibility(View.GONE);
         redirecttemplate.setVisibility(View.GONE);



        btnredirect = (Button)findViewById(R.id.btnredirect);
        btnSubmitTest = (Button)findViewById(R.id.btnSubmitTest);


        btnSubmitTest.setOnClickListener(this);
        btnredirect.setOnClickListener(this);

        helper = new DBHelper(this);
        iQuestionNo = 0 ;
        Submodules = 0;


//addQuestion();

        btnBegin = (Button)findViewById(R.id.btnBeginAptitude);

        btnBegin.setOnClickListener(this);

        btnnext = (Button)findViewById(R.id.btnNextQues);

        btnnext.setOnClickListener(this);

        btnPrev = (Button)findViewById(R.id.btnPrevQues);
        btnPrev.setOnClickListener(this);

        initialize();
    }

    public void initialize()
    {
         Bundle extras = getIntent().getExtras();

          if (extras != null)
          {
              strStudentIDfromPrevPage = extras.getString("StudentID");

                strselected_StudentID = strStudentIDfromPrevPage;
          }
              else 
              {
                 Toast.makeText(getBaseContext(),  "no id found", Toast.LENGTH_LONG).show();
              }
    }


     public int getcount(String moduleID, Integer SubModuleID)
     {
         count = 0;
         String selectQuery = "Select * from AT_QuestionMaster where ModuleID = "+moduleID+" AND SubModuleID ="+SubModuleID;

            SQLiteDatabase db = helper.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);
            count =  cursor.getCount();

           // Toast.makeText(this, String.valueOf(count) ,Toast.LENGTH_LONG).show(); 

            cursor.close();
            db.close();

    return count; 
     }

       private void Getoptions() {
            // database handler
            DBHelper db = new DBHelper(getApplicationContext());

            // Spinner Drop down elements
             List<String> options = db.getAllOptions(QuestionID);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, android.R.id.text1, options);

            listviewoptions.setAdapter(adapter);

            //Toast.makeText(this,"",Toast.LENGTH_LONG).show();
        }

       @Override
       public boolean onKeyDown(int keyCode, KeyEvent event) {
           if ((keyCode == KeyEvent.KEYCODE_BACK)) {
               AlertDialog.Builder alertbox = new AlertDialog.Builder(Aptitude.this);

               alertbox.setTitle("Back is not allowed during Assessment. Please Contact Assessor");
               alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface arg0, int arg1) { 
                      // finish used for destroyed activity
                    //   finish();
                //     exit();
                    //  Toast.makeText(Interest.this, "Back is not  ", Toast.LENGTH_LONG).show();
                   }
               });

               alertbox.show();
           }

           return super.onKeyDown(keyCode, event);
       }


       public void getAllQuestionsAptitude(String moduleID, Integer SubModuleID,String SubModuleQuestion_ID){


           SQLiteDatabase db = helper.getReadableDatabase();
           Cursor c = null;

           if (count>0)
            {

           //   SubModuleQuestion_ID = "1";
                   String selectQuestion = "Select * from AT_QuestionMaster where ModuleID = "+moduleID+" AND SubModuleID ="+SubModuleID+" AND QuestionSequence ="+SubModuleQuestion_ID;
                      c = db.rawQuery(selectQuestion, null);
            if (c.moveToFirst()) {
                do {

                    QuestionNo = c.getString(c.getColumnIndex("QuestionSequence")); 


                    QuestionID = c.getString(c.getColumnIndex("QuestionNo"));   

                    Title = c.getString(c.getColumnIndex("Title"));   

                    TitleDescription = c.getString(c.getColumnIndex("TitleDescription"));             

                    QuestionText = c.getString(c.getColumnIndex("QuestionText"));         

                    QuestionTemplate = c.getString(c.getColumnIndex("QuestionTemplate"));

                    QuestionImage = c.getString(c.getColumnIndex("QuestionImage"));

                    stroptiontitle = c.getString(c.getColumnIndex("Title"));

                    Getoptions();

                } while (c.moveToNext());        
            }
            }
            else
            {
                 Toast.makeText(this,"NO question to display",Toast.LENGTH_LONG).show();
            }

            c.close();
            db.close();
        }

       public void displayquestions()
       {

    //     Toast.makeText(this,"count on display Q is"+ count,Toast.LENGTH_LONG).show();
           if (count >0)
           {
               getAllQuestionsAptitude("3",Submodules,String.valueOf(iQuestionNo));

//                  aptitudesubcateg.setVisibility(View.GONE);
                    temp5optimage.setVisibility(View.VISIBLE);

                    tvTitle = (TextView)findViewById(R.id.tvTitleAptitude);
                    tvQuestionNoAptitude  = (TextView)findViewById(R.id.tvQuestionNoAptitude);
                    tvInstructions = (TextView)findViewById(R.id.tvInstructionsAptitude);
                    tvQuestionText = (TextView)findViewById(R.id.tvQuestionAptitude);

                    tvOptiontitle = (TextView)findViewById(R.id.txtOptionTitle);
                    tvTimer = (TextView)findViewById(R.id.txtTimerAptitude);
                  //  tvTimer.setText("15:00");   


                    img = (ImageView)findViewById(R.id.imgAptitude);

                    tvTitle.setText(Title);
                    tvQuestionNoAptitude.setText(QuestionNo+". ");
                //  tvInstructions.setText(TitleDescription);
                    tvOptiontitle.setText(stroptiontitle);
                    tvQuestionText.setText(QuestionText);

                    String imgName = QuestionImage; // specify here your image name fetched from db
                    if (imgName != null)
                    {
                        img.setVisibility(View.VISIBLE);
                    int resourceId = this.getResources().getIdentifier(imgName, "drawable", "com.cldonline.assesmenttool");
                    img.setImageResource(resourceId);
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)tvOptiontitle.getLayoutParams();

                     tvOptiontitle.setLayoutParams(params);

                     RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)listviewoptions.getLayoutParams();

                     tvOptiontitle.setLayoutParams(params1);
                    }
                    else
                    {
                        img.setVisibility(View.GONE);
//                      RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)tvOptiontitle.getLayoutParams();
//                       params.setMargins(0, 0, 0, 170); //left, top, right, bottom);
//                       
//                       tvOptiontitle.setLayoutParams(params);
//                       
//                       RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)listviewoptions.getLayoutParams();
//                       params1.setMargins(0, 20, 0, 190); //left, top, right, bottom);
//                       tvOptiontitle.setLayoutParams(params1);

                    }
           }
           else
           {
//             aptitudesubcateg.setVisibility(View.GONE);
                  temp5optimage.setVisibility(View.GONE);
                  redirecttemplate.setVisibility(View.VISIBLE);
              // Toast.makeText(this,"NO question to display",Toast.LENGTH_SHORT).show();
               Intent i = new Intent(getApplicationContext(),Thankyou.class);

                startActivity(i); 
                overridePendingTransition(R.anim.slide_in,
                        R.anim.slide_out);
           }

           if(count == iQuestionNo)
           {  
                 btnnext.setEnabled(false);
                 String selectedColor = "#F5AD82";
                 btnnext.setBackgroundColor(Color.parseColor(selectedColor));
                 btnnext.setTextColor(Color.LTGRAY);
           }
       }

       public void NextQuestion()
       {
           if(response == 0)
           {
               iQuestionNo++;
                response = 0;
                  displayquestions();
           }
           //if (count>0 && response > 0)
           if (count>=iQuestionNo && response > 0)
           {
           //count = count - 1;
               iQuestionNo++;
           saveQuestion();

           }
           //if (count == 0)
           if(count<iQuestionNo)
           {  
                  temp5optimage.setVisibility(View.GONE);
                  redirecttemplate.setVisibility(View.VISIBLE);
           }
       }

       public void getoptionSelected(String StudentIDResponse , String QuestionIDResponse)
       {
           SQLiteDatabase db = helper.getReadableDatabase();
           Cursor c = null;
           String selectQuestion = "Select * from TableResponse where StudentID = "+StudentIDResponse+" AND QuestionID ="+QuestionIDResponse;
          c = db.rawQuery(selectQuestion, null);
        if(  c.getCount() >0) {
         if (c.moveToFirst()) {
                do {


                 strOptionResponseID = c.getString(c.getColumnIndex("QuestOptionID"));  


                } while (c.moveToNext());        
            }
        }
        else
        {
            //No response Found
        }
       }

       public void PrevQuestion()
       {
           getoptionSelected(strselected_StudentID,QuestionID);
           //strOptionResponseID
           if (strOptionResponseID !=null)
           {

                 int iposition = Integer.parseInt(strOptionResponseID)-1;
                Toast.makeText(this,String.valueOf(iposition) ,Toast.LENGTH_LONG).show();
                //  response = Integer.parseInt(strOptionResponseID);
                  String Selectedcolor = "#fdc500";
                listviewoptions.getChildAt(iposition).setBackgroundColor(Color.parseColor(Selectedcolor));
           }

           if(response == 0)
           {
               iQuestionNo--;
                response = 0;
                  displayquestions();
           }
           //if (count>0 && response > 0)
           if (count>=iQuestionNo && response > 0)
           {
           //count = count - 1;
               iQuestionNo--;
           saveQuestion();

           }
           //if (count == 0)
           if(count<iQuestionNo)
           {
              // aptitudesubcateg.setVisibility(View.GONE);
                  temp5optimage.setVisibility(View.GONE);
                  redirecttemplate.setVisibility(View.VISIBLE);
               //   Submodules =  Submodules +1;

           }      
       }



       public void saveQuestion()
       {
           if (response != 0)
           {
               String Selectquery = "Select _id from TableResponse Where StudentID ="+strselected_StudentID+" AND QuestionID ="+QuestionID;

                SQLiteDatabase db = helper.getReadableDatabase();
                Cursor cursor = db.rawQuery(Selectquery, null);
                int count =  cursor.getCount();
                String strID = "";
                if( count >0) {
                     if (cursor.moveToFirst()) {
                        do {
                          strID = cursor.getString(cursor.getColumnIndex("_id"));   


                        } while (cursor.moveToNext());        
                    }
             //   Toast.makeText(this, String.valueOf(count) ,Toast.LENGTH_LONG).show(); 

                cursor.close();
                db.close();
                }

               if (strID == "")
               {
               //StudentID = 100;
               ContentValues values = new ContentValues();
            //  values.put(DBHelper.Q_ID, "a");

                values.put(DBHelper.StudentID,strselected_StudentID);
                values.put(DBHelper.R_QuestionID,QuestionID);
                values.put(DBHelper.QuestOptionID,String.valueOf(response));

                db = helper.getWritableDatabase();
                db.insert(DBHelper.TABLEResponse, null, values);
                db.close();             

                response = 0;
                  displayquestions();
           }

           else
           {
               ContentValues values = new ContentValues();

                values.put(DBHelper.QuestOptionID,String.valueOf(response));    

                db = helper.getWritableDatabase();
                db.update(DBHelper.TABLEResponse, values, DBHelper.R_ID + "=?",
                        new String[] { strID });
                db.close();
           }
           }
           else
           {
                Toast.makeText(this, "Please Select an option",
                        Toast.LENGTH_LONG).show();
           }
       }

       public class CounterClass extends CountDownTimer {
             public CounterClass(long millisInFuture, long countDownInterval)
             { 
             super(millisInFuture, countDownInterval);
             }
             @Override public void onFinish() 
             { 
             tvTimer.setText("Time Up !!");
             } 

              @Override 
             public void onTick(long millisUntilFinished) 
             {

                  tvTimer.setText(""+String.format("%d : %d left", 
                        TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - 
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
             }
             }



    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (v==btnBegin)
        {
            btnBegin.setEnabled(false);
            //  interestsubcateg.setVisibility(View.VISIBLE);
                  temp5optimage.setVisibility(View.VISIBLE);
                  if (Submodules == 0)
                  {
                  Submodules = 1;
                  }

                  getcount("3", Submodules);

                  iQuestionNo=1;
                  displayquestions();
                    timer  = new CounterClass(900000,1000);
                  //  tvTimer.setText("15:00"); 
                 //   timer.cancel();

                   tvTimer.setText("15:00"); 

                    timer.start();
        }       


            if (v== btnnext)
            {
                NextQuestion();
            }

            if (v==btnredirect)
            {
//              aptitudesubcateg.setVisibility(View.GONE);
                  temp5optimage.setVisibility(View.VISIBLE);
                  redirecttemplate.setVisibility(View.GONE);
                   Submodules = Submodules +1;
                  getcount("3", Submodules);
                     //count=getcount("1", Submodules);
                      iQuestionNo=1;
                     displayquestions();
                     timer = new CounterClass(900000,1000);
                        tvTimer.setText("15:00");
                    //   tvTimer.setText("15:00");
                        timer.start();
        }

            if(v== btnPrev)
            {
                PrevQuestion();
            }

            if (v==btnSubmitTest)
            {
                  AlertDialog.Builder alertbox = new AlertDialog.Builder(Aptitude.this);

                   alertbox.setTitle("Do you want to submit the test ?");
                   alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface arg0, int arg1) { 
                          // finish used for destroyed activity


                             temp5optimage.setVisibility(View.GONE);
                              redirecttemplate.setVisibility(View.VISIBLE);
                            //  timer = new CounterClass(900000,1000);
                              timer.cancel();
                              timer.onFinish();
                       }
                   });

                   alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface arg0, int arg1) {
                               // Nothing will be happened when clicked on no button 
                               // of Dialog     
                     }
                   });

                   alertbox.show();
            }
    }
}

更新

public void PrevQuestion()
{
    getoptionSelected(strselected_StudentID,QuestionID);
    //strOptionResponseID
    if (strOptionResponseID !=null)
    {
        int iposition = Integer.parseInt(strOptionResponseID)-1;
        String Selectedcolor = "#fdc500";

        View v = listviewoptions.getChildAt(1); // your index from DB
        v.setBackgroundColor(Color.parseColor(Selectedcolor));
    }

3 个答案:

答案 0 :(得分:1)

使用状态drawable作为列表项背景。设置state_activated的选定颜色。单击列表视图中的项目时,请调用setActivated()方法。

答案 1 :(得分:1)

在需要以编程方式显示选择的地方使用此

View v = listView.getChildAt(index); // your index from DB
v.setBackgroundColor(0xFF00FF00); // Any color you want

我在这里回答了类似的问题List selector not working properly

答案 2 :(得分:1)

您的项目背景的可绘制状态可能如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item
    android:drawable="@color/grey_07" android:state_activated="true" android:state_focused="false" android:state_pressed="false"/>

  <item
    android:drawable="@color/black_alpha_08" android:state_activated="true" android:state_focused="false" android:state_pressed="true"/>

  <item
    android:drawable="@color/orange_alpha_30" android:state_activated="true" android:state_focused="true" android:state_pressed="false"/>

  <item
    android:drawable="@android:color/transparent" android:state_enabled="true" android:state_window_focused="false"/>

  <item android:drawable="@color/black_alpha_08" android:state_pressed="true"/>

  <item
    android:drawable="@color/orange_alpha_30" android:state_enabled="true" android:state_focused="true"/>

  <item
    android:drawable="@android:color/transparent" android:state_enabled="true"/>

  <item
    android:drawable="@color/orange_alpha_30" android:state_focused="true"/>

  <item android:drawable="@android:color/transparent"/>

</selector>

在你的代码中,你触发了一个项目被点击的地方,可能是onclicklistener或onitemclicklistener,在视图上调用以下方法:

yourClickedView.setActivated(true);

希望这有帮助。