簡體   English   中英

設置適配器后調用ListView的getChildAt()方法

[英]Calling getChildAt() method of ListView after setting Adapter

我在調用ListView的setAdapter()之后嘗試運行ListView.getChildAt()方法,但是它給了我NullPointerException 似乎設置適配器不會導致創建子視圖。 如下方法所示,我試圖獲取子視圖,以便可以更改其背景顏色。 我該如何解決這個問題?

private void showAnswers(int questionLocation)
{
    List<Answer> answers = getAnswersByQuestionLocation(questionLocation);

    ArrayAdapter<String> answerAdapter = new ArrayAdapter<String>(this,
                                    android.R.layout.simple_list_item_activated_1);

    for (int i = 0; i < answers.size(); i++)
    {
        answerAdapter.add(mOptionLetters[i] +". "+ answers.get(i).getAnswerText());
    }

    mAnswerList.setAdapter(answerAdapter);

    if (mAnswerLocationByQuestionLocation.indexOfKey(questionLocation) > -1)
    {
        Log.v("Child Count",String.valueOf(mAnswerList.getChildCount()));

            //mAnswerList.getChildAt(
            //       mAnswerLocationByQuestionLocation.get(questionLocation))
            //      .setSelected(true);
    }
}

如果只是需要更改背景,請按以下步驟操作:

    ArrayAdapter<String> answerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_activated_1) {
        @Override
        public View getView(int position, View convertView,
                ViewGroup parent) {
            View v =super.getView(position, convertView, parent);;
            v.setBackgroundColor(Color.RED);
            return v;
        }

    };

因為您在UI線程上運行,所以listView將需要足夠的時間在該線程的下一個循環中創建視圖,但是您無法猜測何時。 所以最好的方法是在適配器中覆蓋getView ,因為適配器使用childs來填充listView :)


class MyModel {

           public MyMode(String txt){
             this.txt = txt
            }

        public String txt;
        public boolean isSelected;

        @Override
        public String toString() {
            return txt;
        }
    }

ArrayAdapter<MyModel> answerAdapter = new ArrayAdapter<MyModel>(this,
        android.R.layout.simple_list_item_activated_1) {
    @Override
    public View getView(int position, View convertView,
            ViewGroup parent) {
        View v =super.getView(position, convertView, parent);;
        MyModel  model = getItem(position);
        if(model.isSelected){
           v.setBackgroundColor(Color.RED);} 
         else{
           v.setBackgroundColor(Color.WHITE);}
        return v;
    }

};

answerAdapter.add(new MyModel(mOptionLetters[i] +". "+ answers.get(i).getAnswerText()));

if (mAnswerLocationByQuestionLocation.indexOfKey(questionLocation) > -1)
    {
        MyModel model = (MyModel)mAnswerList.getItemAtPosition(questionLocation);
    model.isSelected= true;
    answerAdapter.notifyDataSetChanged();

    }
}

無論如何,您都需要閱讀有關ListViews和適配器的本教程http://www.vogella.com/articles/AndroidListView/article.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM