更改选择/单击列表视图项的背景 - Android [英] Change the Background of Select/Click listview Item - Android

查看:18
本文介绍了更改选择/单击列表视图项的背景 - Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 quiz application.为此,我使用 listview 来显示答案选项,我想在用户选择listview 项目,如果答案是 正确 然后设置 green backgroundwrong 然后设置 red background

I am working on the quiz application.For that I am using listview for the dispaly the answers options, I want to change the listview background color when user select the listview item, If answer is correct then set the green background and wrong then set red background

我想了很多,但我没有得到解决方案.

I am tring so much, but i don,t get the solution.

适配器类

public class ListviewAdapter extends BaseAdapter{

public List<String> Questions;  

public Activity context;  
public LayoutInflater inflater;
private int[] colors = new int[] { 0x30505050, 0x30808080 };

private String[] opt_no;
public static View change_color;

public ListviewAdapter(Activity context,List<String> answers, String[] que_opt_no) {  
    super();  

    this.context = context;  
    this.Questions = answers; 
    this.opt_no = que_opt_no;

    //this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
}  

@Override  
public int getCount() {  
    // TODO Auto-generated method stub  
    return Questions.size();  
}  

@Override  
public Object getItem(int position) {  
    // TODO Auto-generated method stub  
     return Questions.get(position);  
}  

@Override  
public long getItemId(int position) {  
    // TODO Auto-generated method stub  
    return 0;  
}  

public static class ViewHolder  
{  

    TextView txtquestion;  
    TextView txtquestion_no;  
}  

@Override  
public View getView(int position, View convertView, ViewGroup parent) {  
    // TODO Auto-generated method stub  

    ViewHolder holder; 

    LayoutInflater inflater = context.getLayoutInflater();
   // this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    String fontPath = "fonts/Face Your Fears.ttf";

    if(convertView==null)  
    {  
        holder = new ViewHolder();  
        convertView = inflater.inflate(R.layout.quiz_questions_listitem, null);  

        holder.txtquestion = (TextView) convertView.findViewById(R.id.textView_option);
        holder.txtquestion_no = (TextView) convertView.findViewById(R.id.textView_option_no);

       // holder.txtquestion .setTypeface(Typeface.createFromAsset(convertView.getContext().getAssets(),fontPath));

        convertView.setTag(holder);  

    }  
    else  
        holder=(ViewHolder)convertView.getTag(); 


   /* int colorPos = position % colors.length;
    convertView.setBackgroundColor(colors[colorPos]); */

    change_color = convertView;

   // convertView.setBackgroundResource(R.drawable.listview_background);


    holder.txtquestion.setText(Questions.get(position)); 
    holder.txtquestion_no.setText(opt_no[position]); 

    return convertView;  
}  

/*public static void setbackground(){

    String answer = SelectedAnswer.getAnswer();
       if (Display_questions.currentQ.getAnswer().trim().equals(answer.trim()))
    { 

          Toast.makeText(change_color.getContext(), "red",Toast.LENGTH_SHORT).show();
         change_color.setBackgroundResource(R.drawable.listview_background);
        //ListviewAdapter.change_color.setBackgroundResource(R.drawable.listview_background);
        //Display_questions.currentGame.incrementRightAnswers();
    }
    else{

        Toast.makeText(change_color.getContext(), "Blue",Toast.LENGTH_SHORT).show();
        change_color.setBackgroundResource(R.drawable.listview_false_background);
        //Display_questions.currentGame.incrementWrongAnswers();
    }
}*/

}

Java 类

 public class Display_questions extends Activity{

 public static Question currentQ;
  public static GamePlay currentGame;
 ListView listview;

ListviewAdapter adapter;

String que_opt_no[] = {"a) ","b)","c) ","d) "};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.quiz_questions);

             listview = (ListView) findViewById(R.id.questions_list);
        listview.setItemsCanFocus(false);

        GoToNextQuestion();
}

private void GoToNextQuestion() {
    // TODO Auto-generated method stub

    listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {


                String  selectedFromList = (String) listview.getItemAtPosition(pos);

                 SelectedAnswer.setAnswer(selectedFromList);

                 if (!checkAnswer(pos)) return;

                if (currentGame.isGameOver()){

                    Intent i = new Intent(Display_questions.this, Display_result.class);
                    i.putExtra("Timer_Value", TimerTime);
                    startActivity(i); 

                    finish();
                }
                else{

                    GoToNextQuestion();


                } 
            }
          });

     setQuestions();
  }

 private void setQuestions() {

    // set the question text from current question

    String question = currentQ.getQuestion().trim();
    TextView qText = (TextView) findViewById(R.id.txt_questions);
    qText.setText(question);


    // set the available options
    List<String> answers = currentQ.getQuestionOptions();

     adapter = new ListviewAdapter(this,answers,que_opt_no);

     listview.setAdapter(adapter);

}

 static boolean checkAnswer(int selectedPosition) {

    String answer = SelectedAnswer.getAnswer();

    if (answer==null){

        return false;
    }
    else {

         AnswerStates state = AnswerStates.NONE;

        if (currentQ.getAnswer().trim().equals(answer.trim()))
        { 

            //listview.setBackgroundResource(R.drawable.listview_background);

            currentGame.incrementRightAnswers();
            state = AnswerStates.RIGHT;

        }
        else{

            //ListviewAdapter.setbackground();
            currentGame.incrementWrongAnswers();
            state = AnswerStates.WRONG;

        }

        adapter.setSelectedAnswerState(selectedPosition, state);
        adapter.notifyDataSetChanged();

        return true;
    }
}

  }

检查我的图片:1.)2.)

Edit : check My images : 1.) 2.)

推荐答案

我建议采用以下方式:适配器类:添加所选位置及其状态(正确/错误)或颜色的存储,例如:

I would suggest to go with the following way: Adapter class: add storing of selected position and its state (CORRECT/INCORRECT) or color, e.g.:

public class ListviewAdapter extends BaseAdapter{

enum AnswerStates {
    // Colors can be provided also for bg
    WRONG(R.drawable.wrong_bg),
    RIGHT(R.drawable.right_bg),
    NONE(R.drawable.list_item_bg);
    /** Drawable id to be used for answer state */
    private int mBg;

    private AnswerStates(int bg) {
        mBg = bg;
    }

    /** getter for drawabale for answer state */
    int getBg() {
        return mBg;
    }
}
...
/** Position of selected answer */
private int mSelectedPosition = -1;
/** State of selected answer */
private AnswerStates mSelectedAnswerState = AnswerStates.NONE;
...
/** Setter for selected answer */
public void setSelectedAnswerState(int selectedPosition, AnswerStates state) {
    mSelectedPosition = selectedPosition;
    mSelectedAnswerState = state;
}    

@Override  
public View getView(int position, View convertView, ViewGroup parent) {
    ...
    // Your stuff
    ...

    if (position == mSelectedPosition) {
        convertView.setBackgroundResource(mSelectedAnswerState.getBg());
    } else {
        // use default bg
        convertView.setBackgroundResource(AnswerStates.NONE.getBg());
    }

    return convertView;
}
...
}

还有Activity类:

And Activity class:

public class Display_questions extends Activity{
    ...
    // Added position parameter to the function
    static boolean checkAnswer(int selectedPosition) {
        //getSelectedAnswer();

        String answer = SelectedAnswer.getAnswer();

        if (answer==null){

            return false;
        }
        else {

            AnswerStates state = AnswerStates.NONE;

            if (currentQ.getAnswer().trim().equals(answer.trim()))
            { 
               //   here set the background Green color
               currentGame.incrementRightAnswers();
               state = AnswerStates.RIGHT;
            }
            else{
               //   here set the background red color
               //ListviewAdapter.setbackground();
               currentGame.incrementWrongAnswers();
               state = AnswerStates.WRONG;
            }

            adapter.setSelectedAnswerState(selectedPosition, state);
            adapter.notifyDataSetChanged();

            return true;
        }
     }
}

这种方式比另一种答案更可靠,因为即使带有答案的列表被滚动并且视图被列表视图重用,它也可以工作.

This way is more reliable than another answer, because it will work even if list with answers get scrolled and views get reused by list view.

这篇关于更改选择/单击列表视图项的背景 - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆