GetView ArrayAdapter" не вызывается

У меня есть собственный адаптер, и его «getView» не вызывается. Это моя основная деятельность:

public class MainActivity extends Activity {
RelativeLayout mainRelativeLayout;
ListView listViewOne;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String[] values1 = new String[] { " ", "Android", "iPhone", "WindowsMobile" };
    ListArr listArr = new ListArr(this, 3);
    listArr.AddListToListArr(values1);
}

}

это мой адаптер:

public class MyAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private TextView textView;
private ImageView icon;

public MyAdapter(Context context, String[] values) {
    super(context, R.layout.first_row, values);
    this.context = context;
    this.values = values;
}

@Override
public int getCount() {
    return values.length;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView;

    rowView = inflater.inflate(R.layout.first_row, parent, false);
    textView = (TextView) rowView.findViewById(R.id.row_text_view);

    icon.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_launcher));
    textView.setText(values[position]);
    return rowView;
}}

и это класс, который создает список:

public class ListArr {
int indexOfEmptyCellInArr;
ListView[] listArr;
Context context;
LinearLayout mainRelativeLayout;

public ListArr(Context context, int numOFLists) {
    this.listArr = new ListView[numOFLists];
    this.indexOfEmptyCellInArr = 0;
    this.context = context;
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.activity_main, null);
    this.mainRelativeLayout = (LinearLayout) v.findViewById(R.id.main_relative_layout);
}

public void AddListToListArr(String[] stringsOfNewList) {
    ArrayAdapter<String> arrayAdapter = new MyAdapter(context, stringsOfNewList);
    ListView listview = new ListView(context);
    listview.setAdapter(arrayAdapter);
    listArr[indexOfEmptyCellInArr] = listview;
    mainRelativeLayout.addView(listArr[indexOfEmptyCellInArr]);

    indexOfEmptyCellInArr++;
}

public void RemoveLastList(){
    int indexOfListToRemove = indexOfEmptyCellInArr - 1;
    listArr[indexOfListToRemove] = null;
    indexOfEmptyCellInArr--;
}

Почему getView не вызывается? Спасибо!


person roiberg    schedule 21.11.2012    source источник
comment
Я отлаживаю его с помощью точек останова. Я вижу, что он останавливается в MyAdapter и в getCount, но не останавливается в getView.   -  person roiberg    schedule 21.11.2012


Ответы (3)


Вы не добавили mainRelativeLayout в представление содержимого действия. вместо этого вы должны использовать findViewById(), применяя дополнительный LayoutInflater. Использование метода LayoutInflater.inflate() приведет к дополнительному раздуванию макета и создаст новое представление, которое еще не было добавлено в представление списка. поэтому измените свой код на следующий:

public class MainActivity extends Activity {
RelativeLayout mainRelativeLayout;
ListView listViewOne;

@Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] values1 = new String[] { " ", "Android", "iPhone", "WindowsMobile" };
        ListArr listArr = new ListArr(this, this, 3);
        listArr.AddListToListArr(values1);
    }
    }

и класс ListAddr к приведенному ниже коду

public class ListArr {
int indexOfEmptyCellInArr;
ListView[] listArr;
Context context;
Activity activity;
LinearLayout mainRelativeLayout;

public ListArr(Activity activity, Context context, int numOFLists) {
    this.listArr = new ListView[numOFLists];
    this.indexOfEmptyCellInArr = 0;
    this.context = context;
    this.activity = activity;
    this.mainRelativeLayout = (LinearLayout) activity.findViewById(R.id.main_relative_layout);
}

public void AddListToListArr(String[] stringsOfNewList) {
    ArrayAdapter<String> arrayAdapter = new MyAdapter(context, stringsOfNewList);
    ListView listview = new ListView(context);
    listview.setAdapter(arrayAdapter);
    listArr[indexOfEmptyCellInArr] = listview;
    mainRelativeLayout.addView(listArr[indexOfEmptyCellInArr]);

    indexOfEmptyCellInArr++;
}

public void RemoveLastList(){
    int indexOfListToRemove = indexOfEmptyCellInArr - 1;
    listArr[indexOfListToRemove] = null;
    indexOfEmptyCellInArr--;
}
person jeet    schedule 21.11.2012
comment
У нас есть победитель!!! Спасибо большое. но мне не нужно было добавлять общедоступный ListArr (действие действия, контекст контекста, int numOFLists) в действие. Я только изменил конструктор ListArr, как и вы, добавив Activity. Спасибо! - person roiberg; 21.11.2012
comment
да, потому что это представление уже было загружено в окно, но если вы хотите загрузить новый макет или представление, вам нужно будет добавить это представление. - person jeet; 21.11.2012
comment
на самом деле, я вставил этот метод два раза. - person jeet; 21.11.2012
comment
Ну, это был конструктор, который я удалил, и вы можете увидеть это в коде класса класса ListAddr. - person jeet; 21.11.2012

Вы также должны перезаписать метод getItem(int position) в файле ArrayAdapter.

@Override
public String getItem(int position) {
    return values[position];
}
person Adam Monos    schedule 21.11.2012

/** * Адаптер для отображения подсказок о здоровье пациента и врача */

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

    @Override
    public int getPosition(HealthPost item) {
        // TODO Auto-generated method stub
        return super.getPosition(item);
    }

    @Override
    public void notifyDataSetChanged() {
        // TODO Auto-generated method stub
        super.notifyDataSetChanged();
    }

    /** Context of application(here DoctorCommentsActivity object) */
    private Context context;
    /** Used to store parentCommentId in order to show doctor reply */
    private String parentCommentId;
    /** Common list used in both patient comment and doctor reply lists */
    private List<HealthPost> commentsList;
    /** List used to store patient comments */
    private List<HealthPost> patientCommentsList;
    /** List used to store doctor replies */
    private List<HealthPost> doctorCommentsList;
    /** boolean list used to decide icon color for plusOneCommentIcon */
    private List<Boolean> isCommentPlusOneList;
    /**
     * boolean hashmap used to store comment id(key) and if it has
     * reply(value)
     */
    private HashMap<String, Boolean> commentIdHasReplyMap;
    /**
     * boolean hashmap used to store comment id(key) and its plus one
     * count(value)
     */
    private HashMap<String, String> commentIdPlusCountMap;

    /** stores comment id of comment to be deleted or plus oned */
    private String commentId;

    /**
     * stores position of list item in case Internet connection is
     * unavailable
     */
    private int retryForPosition = -1;
    /** stores position of list item in case of right doctor is clicked */
    private int positionValue;

    /**
     * differentiates in two lists whether list stores patient comments or
     * doctor replies
     */
    private boolean isReply = false;

    public HealthTipsAdapter(Context context, List<HealthPost> list) {
        super(context, R.layout.list_health_tips,list);
        this.context = context;
        this.commentsList = new ArrayList<HealthPost>();
        Log.v(tag,"construtor-"+list.get(1).getPost());
        this.commentsList.addAll(list);
    }

    @Override
    public int getCount() {
        Log.v(tag,"size"+commentsList.size());
        return commentsList.size();

    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Log.v(tag,"getview-"+position+"commentlist-"+commentsList.get(1).getPost());
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.list_health_tips,
                parent, false);

        final TextView tv_comment_right_count = (TextView) rowView
                .findViewById(R.id.tv_comment_right_count);

        final View rl_comment_delete = rowView
                .findViewById(R.id.rl_comment_delete);
        final TextView textViewUserName = (TextView) rowView
                .findViewById(R.id.textView_UserName);
        final TextView textViewComment = (TextView) rowView
                .findViewById(R.id.txtComment);
        final TextView textViewDate = (TextView) rowView
                .findViewById(R.id.textView_date);
        final TextView textViewTime = (TextView) rowView
                .findViewById(R.id.textView_time);
        final View rl_comment_right = (View) rowView
                .findViewById(R.id.rl_comment_right);
        final ImageView iv_comment_right = (ImageView) rowView
                .findViewById(R.id.iv_comment_right);
        final View rl_comment_offensive = (View) rowView
                .findViewById(R.id.rl_comment_offensive);
        final View rl_doctor_reply = (View) rowView
                .findViewById(R.id.rl_doctor_reply);
        final ImageView iv_doctor_reply_seperator = (ImageView) rowView
                .findViewById(R.id.iv_doctor_reply_seperator);
        Log.v(tag,"getView-"+commentsList.get(1).getPost());
        // Actual comment text to be displayed
        textViewComment.setText("hi"+commentsList.get(position).getPost());


        return rowView;
    }
person Sandip Lawate    schedule 13.03.2014
comment
я не получаю данные в методе getview .. помогите, пожалуйста - person Sandip Lawate; 13.03.2014