Урок 54. Кастомизация списка. Создаем свой адаптер

Обсуждение уроков
ppp_ppp
Сообщения: 7
Зарегистрирован: 04 янв 2015, 00:56

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение ppp_ppp » 19 мар 2015, 21:47

Foenix писал(а):Обязательно нужен начальный массив значений, пусть даже заполненеый одинак. Значениями. Его и надо потом менять.
Спасибо, то что надо!

Pavel-Pugach
Сообщения: 15
Зарегистрирован: 31 мар 2015, 15:17

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Pavel-Pugach » 02 апр 2015, 19:34

А как в своем адаптере сделать обработку нажатий на пункты списка?

Снимаю вопрос. Нашел. В item.xml нужно прописать атрибут

android:descendantFocusability="blocksDescendants"

Евгений Суханов
Сообщения: 12
Зарегистрирован: 15 мар 2015, 21:55

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Евгений Суханов » 20 апр 2015, 21:02

Ребят, подскажите, уже были вопросы (ответ не нашел). Есть лист адаптер (свой созданный) Пару полей и кнопка Как по кнопке удалять запись из листа?

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 20 апр 2015, 21:51

Евгений Суханов писал(а):Ребят, подскажите, уже были вопросы (ответ не нашел). Есть лист адаптер (свой созданный) Пару полей и кнопка Как по кнопке удалять запись из листа?
Ты передаешь лист обьектов в конструктор. (например ArrayList<MyObject> list;)
просто вызываешь у него list.remove(position)
1) Можно делат ькак в адаптере так и в активити (просто нужно хранить ссылку на лист или на адаптер)
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

Евгений Суханов
Сообщения: 12
Зарегистрирован: 15 мар 2015, 21:55

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Евгений Суханов » 21 апр 2015, 21:47

doter.ua писал(а):
Евгений Суханов писал(а):Ребят, подскажите, уже были вопросы (ответ не нашел). Есть лист адаптер (свой созданный) Пару полей и кнопка Как по кнопке удалять запись из листа?
Ты передаешь лист обьектов в конструктор. (например ArrayList<MyObject> list;)
просто вызываешь у него list.remove(position)
1) Можно делат ькак в адаптере так и в активити (просто нужно хранить ссылку на лист или на адаптер)

Код: Выделить всё

public class Office_adapter extends BaseAdapter{
    Office_adapter(Context context, ArrayList<type_data_user> person, Typeface font2) {
        ctx = context;
        list = person;
        font = font2;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
...
    View.OnClickListener delete = new View.OnClickListener() {
        @Override
                public void onClick(View v) {
                    Toast.makeText(ctx, Integer.toString(list.size()), Toast.LENGTH_LONG).show();
                    list.remove(0);
                    Toast.makeText(ctx, Integer.toString(list.size()), Toast.LENGTH_LONG).show();
                }
    };
При нажатии выводит сначала list.size=1 потом list.size=0; Экран не меняется (не удаляется поле), если зайти заново в этот активити то происходит тоже самое list.size=1 потом list.size=0
Последний раз редактировалось Евгений Суханов 21 апр 2015, 22:33, всего редактировалось 1 раз.

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 21 апр 2015, 22:26

Евгений Суханов писал(а): Почему может не срабатывать? Не удаляется
Что за position_? откуда берешь? скинь весь код адаптера, а то я говорил про ArrayAdapter, у тебя немного другой.
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

Евгений Суханов
Сообщения: 12
Зарегистрирован: 15 мар 2015, 21:55

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Евгений Суханов » 21 апр 2015, 22:33

doter.ua писал(а):
Евгений Суханов писал(а): Почему может не срабатывать? Не удаляется
Что за position_? откуда берешь? скинь весь код адаптера, а то я говорил про ArrayAdapter, у тебя немного другой.

Код: Выделить всё

package john.vsmart;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.ImageButton;
import java.util.ArrayList;

/**
 * Created by Евгений on 24.03.2015.
 */
public class Office_adapter extends BaseAdapter{
    Context ctx;
    View view;
    LayoutInflater lInflater;
    ArrayList<type_data_user> list;
    Typeface font;
    Integer position_;
    ImageButton btn_delete;
    Office_adapter(Context context, ArrayList<type_data_user> person, Typeface font2) {
        ctx = context;
        list = person;
        font = font2;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        view = convertView;
        type_data_user p = getPerson(position);
        if (p.check_teacher) {
            if (view == null) {
                view = lInflater.inflate(R.layout.adapter_office_teacher, parent, false);
            }
            ((TextView) view.findViewById(R.id.office_t_insert_name)).setText(p.name);
            ((TextView) view.findViewById(R.id.office_t_insert_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_last_name)).setText(p.last_name);
            ((TextView) view.findViewById(R.id.office_t_insert_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_father_name)).setText(p.father_name);
            ((TextView) view.findViewById(R.id.office_t_insert_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_phone)).setText(p.phone);
            ((TextView) view.findViewById(R.id.office_t_insert_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_city)).setText(p.city);
            ((TextView) view.findViewById(R.id.office_t_insert_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_exp)).setText(p.class_exp);
            ((TextView) view.findViewById(R.id.office_t_insert_exp)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_subject)).setText(p.subject);
            ((TextView) view.findViewById(R.id.office_t_insert_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_cost)).setText(p.cost);
            ((TextView) view.findViewById(R.id.office_t_insert_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_education)).setText(p.educational);
            ((TextView) view.findViewById(R.id.office_t_insert_education)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_audience)).setText(p.audience);
            ((TextView) view.findViewById(R.id.office_t_insert_audience)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_extra)).setText(p.extraInf);
            ((TextView) view.findViewById(R.id.office_t_insert_extra)).setTypeface(font);

            ((TextView) view.findViewById(R.id.office_t_txt_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_exp)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_educational)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_audience)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_extraInf)).setTypeface(font);


            btn_delete=(ImageButton)view.findViewById(R.id.office_t_btn_delete);
            btn_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(ctx, "fdsfds", Toast.LENGTH_LONG).show();
                }
            });
            position_=position;


            if (p.father_name.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_father_name)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.cost.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_cost)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.educational.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_educational)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.extraInf.equals(""))
            {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_extra_inf)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }

        } else {
            if (view == null) {
                view = lInflater.inflate(R.layout.adapter_office_pupil, parent, false);
            }
            ((TextView) view.findViewById(R.id.office_p_insert_name)).setText(p.name);
            ((TextView) view.findViewById(R.id.office_p_insert_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_last_name)).setText(p.last_name);
            ((TextView) view.findViewById(R.id.office_p_insert_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_father_name)).setText(p.father_name);
            ((TextView) view.findViewById(R.id.office_p_insert_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_phone)).setText(p.phone);
            ((TextView) view.findViewById(R.id.office_p_insert_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_city)).setText(p.city);
            ((TextView) view.findViewById(R.id.office_p_insert_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_class)).setText(p.class_exp);
            ((TextView) view.findViewById(R.id.office_p_insert_class)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_subject)).setText(p.subject);
            ((TextView) view.findViewById(R.id.office_p_insert_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_cost)).setText(p.cost);
            ((TextView) view.findViewById(R.id.office_p_insert_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_extra)).setText(p.extraInf);
            ((TextView) view.findViewById(R.id.office_p_insert_extra)).setTypeface(font);


            ((TextView) view.findViewById(R.id.office_p_txt_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_class)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_extraInf)).setTypeface(font);

            btn_delete=(ImageButton)view.findViewById(R.id.office_p_btn_delete);
            btn_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(ctx, Integer.toString(list.size()), Toast.LENGTH_LONG).show();
                    list.remove(0);
                    Toast.makeText(ctx, Integer.toString(list.size()), Toast.LENGTH_LONG).show();
                }
            });
            position_=position;

            if (p.father_name.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_p_layout_father_name)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.cost.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_p_layout_cost)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.extraInf.equals(""))
            {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_p_layout_extraInf)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
        }
        return view;
    }


    private type_data_user getPerson(int position) {
        return ((type_data_user) getItem(position));
    }
}

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 21 апр 2015, 22:55

после удаления вызови notifydatasetchanged(); Если удаляешь в активити, то myAdapter.notifydatasetchanged();
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

Евгений Суханов
Сообщения: 12
Зарегистрирован: 15 мар 2015, 21:55

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Евгений Суханов » 21 апр 2015, 23:01

Евгений Суханов писал(а):
doter.ua писал(а):
Евгений Суханов писал(а): Почему может не срабатывать? Не удаляется
Что за position_? откуда берешь? скинь весь код адаптера, а то я говорил про ArrayAdapter, у тебя немного другой.

Код: Выделить всё

package john.vsmart;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.ImageButton;
import java.util.ArrayList;

/**
 * Created by Евгений on 24.03.2015.
 */
public class Office_adapter extends BaseAdapter{
    Context ctx;
    View view;
    LayoutInflater lInflater;
    ArrayList<type_data_user> list;
    Typeface font;
    Integer position_;
    ImageButton btn_delete;
    Office_adapter(Context context, ArrayList<type_data_user> person, Typeface font2) {
        ctx = context;
        list = person;
        font = font2;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        view = convertView;
        type_data_user p = getPerson(position);
        if (p.check_teacher) {
            if (view == null) {
                view = lInflater.inflate(R.layout.adapter_office_teacher, parent, false);
            }
            ((TextView) view.findViewById(R.id.office_t_insert_name)).setText(p.name);
            ((TextView) view.findViewById(R.id.office_t_insert_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_last_name)).setText(p.last_name);
            ((TextView) view.findViewById(R.id.office_t_insert_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_father_name)).setText(p.father_name);
            ((TextView) view.findViewById(R.id.office_t_insert_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_phone)).setText(p.phone);
            ((TextView) view.findViewById(R.id.office_t_insert_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_city)).setText(p.city);
            ((TextView) view.findViewById(R.id.office_t_insert_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_exp)).setText(p.class_exp);
            ((TextView) view.findViewById(R.id.office_t_insert_exp)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_subject)).setText(p.subject);
            ((TextView) view.findViewById(R.id.office_t_insert_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_cost)).setText(p.cost);
            ((TextView) view.findViewById(R.id.office_t_insert_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_education)).setText(p.educational);
            ((TextView) view.findViewById(R.id.office_t_insert_education)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_audience)).setText(p.audience);
            ((TextView) view.findViewById(R.id.office_t_insert_audience)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_insert_extra)).setText(p.extraInf);
            ((TextView) view.findViewById(R.id.office_t_insert_extra)).setTypeface(font);

            ((TextView) view.findViewById(R.id.office_t_txt_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_exp)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_educational)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_audience)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_t_txt_extraInf)).setTypeface(font);


            btn_delete=(ImageButton)view.findViewById(R.id.office_t_btn_delete);
            btn_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(ctx, "fdsfds", Toast.LENGTH_LONG).show();
                }
            });
            position_=position;


            if (p.father_name.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_father_name)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.cost.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_cost)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.educational.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_educational)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.extraInf.equals(""))
            {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_t_layout_extra_inf)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }

        } else {
            if (view == null) {
                view = lInflater.inflate(R.layout.adapter_office_pupil, parent, false);
            }
            ((TextView) view.findViewById(R.id.office_p_insert_name)).setText(p.name);
            ((TextView) view.findViewById(R.id.office_p_insert_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_last_name)).setText(p.last_name);
            ((TextView) view.findViewById(R.id.office_p_insert_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_father_name)).setText(p.father_name);
            ((TextView) view.findViewById(R.id.office_p_insert_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_phone)).setText(p.phone);
            ((TextView) view.findViewById(R.id.office_p_insert_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_city)).setText(p.city);
            ((TextView) view.findViewById(R.id.office_p_insert_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_class)).setText(p.class_exp);
            ((TextView) view.findViewById(R.id.office_p_insert_class)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_subject)).setText(p.subject);
            ((TextView) view.findViewById(R.id.office_p_insert_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_cost)).setText(p.cost);
            ((TextView) view.findViewById(R.id.office_p_insert_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_insert_extra)).setText(p.extraInf);
            ((TextView) view.findViewById(R.id.office_p_insert_extra)).setTypeface(font);


            ((TextView) view.findViewById(R.id.office_p_txt_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_last_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_father_name)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_phone)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_city)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_class)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_subject)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_cost)).setTypeface(font);
            ((TextView) view.findViewById(R.id.office_p_txt_extraInf)).setTypeface(font);

            btn_delete=(ImageButton)view.findViewById(R.id.office_p_btn_delete);
            btn_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(ctx, Integer.toString(list.size()), Toast.LENGTH_LONG).show();
                    list.remove(0);
                    Toast.makeText(ctx, Integer.toString(list.size()), Toast.LENGTH_LONG).show();
                }
            });
            position_=position;

            if (p.father_name.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_p_layout_father_name)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.cost.equals("")) {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_p_layout_cost)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
            if (p.extraInf.equals(""))
            {
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) (view.findViewById(R.id.office_p_layout_extraInf)).getLayoutParams();
                params.height = 0;
                params.topMargin = 0;
            }
        }
        return view;
    }


    private type_data_user getPerson(int position) {
        return ((type_data_user) getItem(position));
    }
}
Гениально, благодарю!

Sibirichok
Сообщения: 5
Зарегистрирован: 09 май 2015, 17:08

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Sibirichok » 13 май 2015, 15:27

Здравствуйте, такой вопрос. Как заменить данные в ListView. Я все сделал как в примере, но добавил две кнопки. Одна добавляет в ListView одни данные, а другая другие. Так вот после нажатия поочередно на кнопки в ListView остаются данные с первого нажатия и со второго. А должны только с последнего. Как решить эту проблему?

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 13 май 2015, 20:54

Sibirichok писал(а):Здравствуйте, такой вопрос. Как заменить данные в ListView. Я все сделал как в примере, но добавил две кнопки. Одна добавляет в ListView одни данные, а другая другие. Так вот после нажатия поочередно на кнопки в ListView остаются данные с первого нажатия и со второго. А должны только с последнего. Как решить эту проблему?
Очередной юзер из клуба экстрасенсов? Код скинь.
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

Sibirichok
Сообщения: 5
Зарегистрирован: 09 май 2015, 17:08

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Sibirichok » 19 май 2015, 11:34

doter.ua

С этим вопросом я с горем пополам разобрался. Но у меня возник другой вопрос. В примере показана работа с чекбоксами. Мне же надо заминить чекбоксы на кнопки, но функцию они должны выполнять ту же самую. То есть по нажатию отмечать в корзине что товар был добавлен.

Как переработать код, что бы обрабатывал не чекбоксов, а кнопку?

Код: Выделить всё

  Context ct;
    LayoutInflater lInflater;
    ArrayList <Product> objects;

    BoxAdapter (Context context, ArrayList <Product> products){
        ct = context;
        objects = products;
        lInflater = (LayoutInflater) ct.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount (){
        return objects.size();
    }

    @Override
    public Object getItem(int position){
        return objects.get(position);
    }
    @Override
    public long getItemId (int position) {
        return position;
    }

    public void Clear_Data()
    {
        objects.clear();
    }



    @Override
    public View getView (int position, View convertView, ViewGroup parent){
        View view = convertView;
        if (view == null){
            view = lInflater.inflate(R.layout.item, parent, false);
        }

        Product p = getProduct(position);


        ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
        ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
        ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

        Button bOrder = (Button) view.findViewById(R.id.bOrder);

        /*bOrder.setOnClickListener(myCheckChangList);
        bOrder.setTag(position);

        bOrder.setOnClickListener();
        bOrder.setTag(position);
        bOrder.setFocusable(false);*/


        /*CheckBox cbBox = (CheckBox) view.findViewById(R.id.cbBox);
        cbBox.setOnCheckedChangeListener(myCheckChangList);
        cbBox.setTag(position);
        cbBox.setChecked(p.box);*/

        return view;


    }
    Product getProduct(int position) {
        return ((Product) getItem(position));
    }


    ArrayList<Product> getBox() {
        ArrayList<Product> box = new ArrayList<Product>();
        for (Product p : objects) {
            if (p.box)
                box.add(p);
        }
        return box;
    }

    CompoundButton.OnCheckedChangeListener myCheckChangList = new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {
            getProduct((Integer) buttonView.getTag()).box = isChecked;
        }
    };

}

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 19 май 2015, 16:37

В R.layout.item замени Чбокс на нужную вьюшку.
В адаптере в getView() замени /*CheckBox cbBox = (CheckBox) view.findViewById(R.id.cbBox); на новый элемнт.
Осталось повесить обработчик нажатий и написать логику.
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

Sibirichok
Сообщения: 5
Зарегистрирован: 09 май 2015, 17:08

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Sibirichok » 19 май 2015, 18:03

Так вот, как сделать оброботчик. Я не знаю как к ней обратиться так как она генериться динамически и не имеет явного id (по крайней мере я не знаю как его узнать) + Как узнать что нужно получить данные именно из поля в котором нажата кнопка.

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 19 май 2015, 19:40

В адаптере

Код: Выделить всё

getView(){
   ...
   Button myBtn= (Button) view.findViewById(R.id.myBtn); 
  
   //получаем данные:
   final Product item = getItem(position);

        myBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                item.get...
            }
        });
   ...
}
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

Sibirichok
Сообщения: 5
Зарегистрирован: 09 май 2015, 17:08

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение Sibirichok » 20 май 2015, 15:56

doter.ua, спасибо больше. Но есть проблема, не хочет вызываться метод из onClick.

scherlokholmes88
Сообщения: 3
Зарегистрирован: 22 июн 2014, 07:46

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение scherlokholmes88 » 20 июл 2015, 10:33

У меня есть список задач из учебника по математике.

Код: Выделить всё

private String tasks_arr[] = {
            "00 Задача 1",
            "01 Задача 2",
            "02 Задача 3",
            "03 Задача 4",
            "04 Задача 5",
            "05 Задача 6",
            "06 Задача 7",
            "07 Задача 8",
            "08 Задача 9",
            "09 Задача 10",
    };
У меня решенные номера задач сохраняются в текстовом файле. Есть метод проверяющий решена ли задача ранее, не знаю как потом подкрасить, например, зелёным цветом 1 элемент списка решённую задачу. Я не могу запретить доступ нажатия к отдельным элементам списка. Сначала открыть доступ (разрешить нажимать на задачу) к первым 5 элементам списка, пока пользователь не решит хотя бы 3 задачи, не давать ему возможности нажать на 6 по 8 задачу. При решении 6 задач открыть ему полный доступ ко всем элементам списка.
Полный код прикладываю ниже
"MainActivity.java"

Код: Выделить всё

public class MainActivity extends ListActivity{

    private ListView lv1; //даем название listview - lv1

    private String[] lv_arr=new String[]{"Задача 1","Задача 2","Задача 3","Задача 4","Задача 5", "Задача 6",
            "Задача 7","Задача 8","Задача 9","Задача 10","Задача 11","Задача 12","Задача 13",
            "Задача 14","Задача 15","Задача 16","Задача 17","Задача 18","Задача 19",
            "Задача 20","Задача 21","Задача 22","Задача 23","Задача 24","Задача 25","Задача 26",
            "Задача 27","Задача 28","Задача 29"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Custom_view cv=new Custom_view(this,lv_arr);
        setListAdapter(cv);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        super.onListItemClick(l, v, position, id);

        // getting the value of clicked item
        String clicked_item = (String) getListAdapter().getItem(position);

        //Позиция элемента, по которому кликнули
        String itemname = new Integer((position)+1).toString();

        //Создаем новый intent
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, ViewActivity.class);
        Bundle b = new Bundle();
        b.putString("defStrID", itemname); //defStrID - уникальная строка, отправим itemname в другое Activity
        intent.putExtras(b);
        startActivity(intent); //запускаем intent
    }
}
"Custom_view.java"

Код: Выделить всё

public class Custom_view extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;

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

    public Boolean checkExistNum(Context ctx)
    {
        Boolean exist=false;

        try {
            FileInputStream inputStream = ctx.openFileInput("events.txt");

            if (inputStream != null) {
                InputStreamReader isr = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(isr);
                String str;

                while ((str = reader.readLine()) != null) {

                }
                inputStream.close();
            }
        } catch (Throwable t) {
            Toast.makeText(context,
                    "checkExistNum Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }
        return exist;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.list_activity, parent, false);
        TextView tv = (TextView) rowView.findViewById(R.id.label);
        String item_value = values[position];

        tv.setText(item_value);

        if(position+1>7)
        {
            rowView.setEnabled(true);
        }

        try {
            FileInputStream inputStream = context.openFileInput("events.txt");

            if (inputStream != null) {
                InputStreamReader isr = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(isr);
                String str;

                while ((str = reader.readLine()) != null) {
                    if(str.equals(position+1))
                    {
                     rowView.setBackgroundColor(Color.GREEN);
                    }
                }
                inputStream.close();
            }
        } catch (Throwable t) {
            Toast.makeText(context,
                    "checkExistNum Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }


        /*if (position % 2 == 0) {
            rowView.setBackgroundColor(Color.parseColor("#ffffff"));
            rowView.setEnabled(false);
        } else {
            rowView.setBackgroundColor(Color.parseColor("#BCF7F0"));
        }*/
        return rowView;
    }
}
"ViewActivity.java"

Код: Выделить всё

public class ViewActivity extends ActionBarActivity {

    private EditText text;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE); //скрываем заголовок

        setContentView(R.layout.view);
        text=(EditText)findViewById(R.id.editText);

        //скрываем статус бар:
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        Bundle bundle = getIntent().getExtras();
        String itemName = "n" + bundle.getString("defStrID"); //получаем строку и формируем имя ресурса

        Context context = getBaseContext(); //получаем контекст

        //читаем текстовый файл из рексурсов по имени
        String text = readRawTextFile(context, getResources().getIdentifier(itemName, "raw", "ru.scherlokdevelop.zadachniktext"));

        WebView myWebView = (WebView) findViewById(R.id.webView);
        //String summary = "<html><body>" + text + "</body></html>";
        //myWebView.loadData(summary, "text/html", "windows-1251"); //загружаем текст в webview
        myWebView.loadDataWithBaseURL(null,text,"text/html","utf-8",null);
    }


    public static String readRawTextFile(Context ctx, int resId) //читаем текст из raw - аргументы контекст и идентификатор ресурса
    {
        InputStream inputStream = ctx.getResources().openRawResource(resId);

        InputStreamReader inputReader = new InputStreamReader(inputStream);
        BufferedReader buffReader = new BufferedReader(inputReader);
        String line;
        StringBuilder text = new StringBuilder();

        try {
            while (( line = buffReader.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        } catch (IOException e) {
            return null;
        }
        return text.toString();
    }

    private void readRawAnswersTextFile(Context ctx,String selNum)
    {
        int pos;
        String buf,ans;
        try {
            InputStream inStream = ctx.getResources().openRawResource(R.raw.answers);
            if (inStream != null) {
                InputStreamReader tmp = new InputStreamReader(inStream);
                BufferedReader reader = new BufferedReader(tmp);
                String str;
                StringBuffer buffer = new StringBuffer();
                while ((str = reader.readLine()) != null) {
                    buffer.append(str + "\n");
                       pos=str.indexOf(' ');
                       buf=str.substring(0, pos);
                       ans=str.substring(pos + 1, str.length());
                       if (buf.equals(selNum)){
                           if(text.getText().toString().equals(ans))
                           {
                               Toast.makeText(ctx,"Ответ верный!!!",Toast.LENGTH_LONG).show();
                               checkEventsTextFile(ctx,selNum);
                               //str=null;
                               //break;
                           }
                           else
                           {
                               Toast.makeText(ctx,"Ответ неверный!",Toast.LENGTH_LONG).show();
                               //str=null;
                               //break;
                           }
                           break;
                       }
                }
                inStream.close();
            }
        }
        catch (Throwable t){
            Toast.makeText(this,"err "+t.toString(),Toast.LENGTH_LONG).show();
        }
    }

    public Boolean checkExistNum(Context ctx,String selNum)
    {
        Boolean exist=false;

        try {
            InputStream inputStream = openFileInput("events.txt");

            if (inputStream != null) {
                InputStreamReader isr = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(isr);
                String str;

                while ((str = reader.readLine()) != null) {
                    if (str.equals(selNum)) {
                        Toast.makeText(ctx, "Задача уже решена", Toast.LENGTH_LONG).show();
                        exist = true;
                        //str = null;
                        break;
                    }
                }
                inputStream.close();
            }
        } catch (Throwable t) {
            /*Toast.makeText(getApplicationContext(),
                    "checkExistNum Exception: " + t.toString(), Toast.LENGTH_LONG).show();*/
            try {
                OutputStream outputStream = openFileOutput("events.txt", 0);
                OutputStreamWriter osw = new OutputStreamWriter(outputStream);
                osw.write(selNum+"\n");
                osw.close();
            } catch (Throwable p) {
                Toast.makeText(ctx,
                        "checkExistNum Exception: " + p.toString(), Toast.LENGTH_LONG).show();
            }
        }
        return exist;
    }

    private void checkEventsTextFile(Context ctx,String selNum) //читаем текст из raw - аргументы контекст и идентификатор ресурса
    {
        //InputStream inputStream = "events.txt").Ex
        //найти метод проверки наличия файла в raw
        if (!checkExistNum(ctx,selNum))
        {
            saveRawEventsTextFile(ctx, selNum);
        }
    }

    private void saveRawEventsTextFile(Context ctx,String selNum) //читаем текст из raw - аргументы контекст и идентификатор ресурса
    {
        try {
            OutputStream outputStream = openFileOutput("events.txt", 0);
            OutputStreamWriter osw = new OutputStreamWriter(outputStream);
            osw.write(selNum+"\n");
            osw.close();
        } catch (Throwable t) {
            Toast.makeText(ctx,
                    "saveRawEv Exception: " + t.toString(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void button1Click(View v)
    {
        Bundle bundle = getIntent().getExtras();
        Context context = getBaseContext();
        readRawAnswersTextFile(context, bundle.getString("defStrID"));
    }
}
"view.xml"

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3">

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:weightSum="1"
            android:layout_weight="1">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Введите ответ:"
                android:id="@+id/textView" />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/editText"
                android:layout_weight="0.28"
                android:inputType="text" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="right">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Проверить ответ"
                android:id="@+id/button"
                android:onClick="button1Click" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
"list_activity.xml"

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="15dp"
        android:text=""
        android:textAllCaps="true"
        android:textSize="20dp" >
    </TextView>

</LinearLayout>
Последний раз редактировалось scherlokholmes88 20 июл 2015, 10:54, всего редактировалось 2 раза.

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 20 июл 2015, 10:51

scherlokholmes88 писал(а):У меня есть список задач из учебника по математике.

Код: Выделить всё

private String tasks_arr[] = {
            "00 Задача 1",
            "01 Задача 2",
            "02 Задача 3",
            "03 Задача 4",
            "04 Задача 5",
            "05 Задача 6",
            "06 Задача 7",
            "07 Задача 8",
            "08 Задача 9",
            "09 Задача 10",
    };
У меня решенные номера задач сохраняются в текстовом файле. Есть метод проверяющий решена ли задача ранее, не знаю как потом подкрасить, например, зелёным цветом 1 элемент списка решённую задачу. Я не могу запретить доступ нажатия к отдельным элементам списка. Сначала открыть доступ (разрешить нажимать на задачу) к первым 5 элементам списка, пока пользователь не решит хотя бы 3 задачи, не давать ему возможности нажать на 6 по 8 задачу. При решении 6 задач открыть ему полный доступ ко всем элементам списка.
В своем классе контейнере добавь булку и число (инт) для настройки элементов в гет вью адаптера.
Первая для вкл\выкл онклик listener.
Число для цвета: int a = R.color.homework_success;

В активити меняешь эти значения в своем листе (который передавал в адаптер) и обновляешь адаптер. notifydatasetchanged..()

ЗЫ можно без дополнительных переменных, если захардкодить ифами в гетвью иф решено сет колор1 елси колор2
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

scherlokholmes88
Сообщения: 3
Зарегистрирован: 22 июн 2014, 07:46

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение scherlokholmes88 » 20 июл 2015, 11:01

Я привёл выше полный код своего задачника. Помогите пожалуйста. И у меня вопрос как сохранять файл в папку raw? Весь инет обрыл, но не нашёл. Я пытался по position в getView закрасить строку.

Аватара пользователя
doter.ua
Сообщения: 1106
Зарегистрирован: 23 ноя 2013, 16:08
Откуда: Ukraine

Re: Урок 54. Кастомизация списка. Создаем свой адаптер

Сообщение doter.ua » 23 июл 2015, 15:29

scherlokholmes88 писал(а):Я привёл выше полный код своего задачника. Помогите пожалуйста. И у меня вопрос как сохранять файл в папку raw? Весь инет обрыл, но не нашёл. Я пытался по position в getView закрасить строку.
Какой-то треш, а не код. Храни задачи в БД:
ид - число
имя - текст
решена\нет - число (1 или 0 ).
Если есть возможность, то подготавливай данные перед инициализацией адаптера, зачем при каждой прорисовке элемента дергать файловую систему, создавая потоки. ЗЫ при скролинге списка элементы будут прорисовываться по новой, т.е. будут вызываться твои "неоптимизированные"проверки. Да и вообще, с БД таких проблем не будет, сверяешься с полем и все.

ЗЫЫ Custom_view - в джава классы так не называют. Нужно с большой буквы + Гугл: "camel case".
Семь раз отмерь - поставь студию.
Эклипс не студия, ошибка вылетит - не исправишь.
Скажи мне кто твой друг, и оба поставили студию.
Студия - свет, а эклипс - тьма.

Ответить