Адаптер Android не обновляет пользовательский интерфейс

У меня есть класс ведьма содержит некоторые переменные... например

 int yellow = 0xffffff66;
 int green = 0xff00EE76;
 int red = 0xffff4342;
 int blue = 0xff42c3ff;
 int purple = 0xff9932CC;
 int white = 0xffffffff;
 ArrayList<Integer>nextColorArray = new ArrayList<Integer>();

интервал общее_счетчик = 0;

в моем методе onCreate:

GridView gridview2 = (GridView) findViewById(R.id.colorNext);
gridview2.setAdapter(new ImageAdapter(this));
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);

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

у меня есть событие кнопки onclick (не в onCreate), которое увеличивает total_count на 1 каждый раз, когда я нажимаю кнопку ... хорошо, когда total_count больше десяти, я хочу добавить новый элемент в массив .. хорошо

if (action == MotionEvent.ACTION_DOWN) {
   if(total_Count > 10){
       nextColorArray.add(0, white);  
}...ok

моя проблема в том, что gridview пользовательского интерфейса не обновляет пользовательский интерфейс, чтобы показать новый цвет... какие-либо идеи о том, как я могу обновить адаптер, когда новый цвет добавляется в список????

Редактировать: так как я не уверен, сколько правок я внес в свой пост. я отредактировал вопрос и добавил ответ здесь. Это работает .

public class MainActivity extends Activity {
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
int white = 0xFFFFFFFF;

int total_Count = 0;
int colorPosition = 0;
int colorPickerStart = 0;
Button button;

ImageView imageView;

ImageAdapter ia;
GridView gridview2;

ArrayList<Integer>nextColorArray = new ArrayList<Integer>(10);
ArrayList<Integer>colorPicker = new ArrayList<Integer>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
//set adapters
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ButtonAdapter(this));
button = (Button) findViewById(R.id.button1); 
gridview2 = (GridView) findViewById(R.id.gridview2);
ia = new ImageAdapter(this, nextColorArray);
gridview2.setAdapter(ia);
button.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                        nextColorArray.add(Color.BLACK);
                        ia.notifyDataSetChanged();

            }
        });
//next color elements


}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<Integer> a;

public ImageAdapter(Context c, ArrayList<Integer> a) {
    mContext = c;
    this.a = a;
}
public int getCount() {

    return a.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return 0;
}

/*create a new ImageView for each item referenced by the Adapter*/
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {/*if it's not recycled, initialize some attributes*/
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(50, 45));
        imageView.setBackgroundColor(nextColorArray.get(colorPosition));
        if(colorPosition < 9) colorPosition++;
    } else {
        imageView = (ImageView) convertView;
    }
    return imageView;
}

}
/*button adapter*/
public class ButtonAdapter extends BaseAdapter {
private Context mContext;

public ButtonAdapter(Context c) {
    mContext = c;
}

public int getCount() {

    return nextColorArray .size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return 0;
}

// create a new button for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {

        button = new Button(mContext);
        button.setLayoutParams(new GridView.LayoutParams(128, 128));

        total_Count++;
        button.setText(""+total_Count); 
    } else {
        button = (Button) convertView;
    }
    return button;
}// end get view
}// end button adapter

Activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:columnWidth="0dp"
    android:gravity="center"
    android:numColumns="2"
    android:horizontalSpacing="20dp"
    android:padding="40dp"
    android:verticalSpacing="20dp" />
     <GridView
    android:id="@+id/gridview2"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_above="@+id/button1"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="74dp"
    android:columnWidth="0dp"
    android:gravity="center"
    android:horizontalSpacing="20dp"
    android:numColumns="2"
    android:padding="40dp"
    android:verticalSpacing="20dp" >
</GridView>


<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="Button" />


</RelativeLayout>

person Community    schedule 20.05.2013    source источник
comment
Я собираюсь отредактировать ваш вопрос с ответом   -  person Raghunandan    schedule 20.05.2013
comment
@ronac, в чем проблема?   -  person Raghunandan    schedule 21.05.2013


Ответы (2)


Вы должны вызвать notifyDataSetChanged() на своем адаптере, чтобы обновить его содержимое.

person Ahmad    schedule 20.05.2013

 ImageAdapter ia;
 GridView gridview2 = (GridView) findViewById(R.id.colorNext);
 ia = new ImageAdapter(this);
 gridview2.setAdapter(ia);  
 .... 
 if (action == MotionEvent.ACTION_DOWN) {
 if(total_Count > 10){
   nextColorArray.add(0, white); 
   ia.notifyDataSetChanged(); // call notifyDataSetChanged  to update your gridview
 }

public void notifyDataSetChanged()

Уведомляет присоединенных наблюдателей о том, что базовые данные были изменены, и любое представление, отражающее набор данных, должно обновиться.

Пример:

Activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:columnWidth="0dp"
    android:gravity="center"
    android:numColumns="2"
    android:horizontalSpacing="20dp"
    android:padding="40dp"
    android:verticalSpacing="20dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="Button" />

    </RelativeLayout>

Основная деятельность

  public class MainActivity extends Activity {

ImageAdapter im;
ImageView imageView;
GridView gd;
 ArrayList<Integer>nextColorArray = new ArrayList<Integer>(); 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     int yellow = 0xffffff66;
     int green = 0xff00EE76;
     int red = 0xffff4342;
     int blue = 0xff42c3ff;
     int purple = 0xff9932CC;
     final int white = 0xffffffff;
     nextColorArray.add(blue);
     nextColorArray.add(green);
     nextColorArray.add(red);
     nextColorArray.add(yellow);
     nextColorArray.add(purple);
        gd= (GridView) findViewById(R.id.gridview);
        im = new ImageAdapter(this,nextColorArray);
        gd.setAdapter(im);
     Button b= (Button) findViewById(R.id.button1);
     b.setOnClickListener(new OnClickListener()
     {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            nextColorArray.add(Color.BLACK);
            im.notifyDataSetChanged();

        }

     });
}
}

Адаптер изображения

   public class ImageAdapter extends BaseAdapter{

Context mContext;
ArrayList<Integer> a;

public ImageAdapter(Context context,ArrayList<Integer> a)   {
    mContext=context;
    this.a= a;
}

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

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

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

@Override
public View getView(final int position, View arg1, ViewGroup arg2) {
     ImageView imageView;
        if (arg1 == null) {  
            imageView = new ImageView(mContext);

            imageView.setPadding(0, 20, 0, 0);
        } else {
            imageView = (ImageView) arg1;
        }

        imageView.setBackgroundColor(a.get(position));

        return imageView;

}
 }

Как и при нажатии черный цвет появляется на экране.

Снимок

введите здесь описание изображения

person Raghunandan    schedule 20.05.2013
comment
Привет, Рагунандан, спасибо за ответ. iv реализовал ваш код, но все равно без радости :(... - person ; 20.05.2013
comment
@ronanc я сделал образец, который работает. Пожалуйста, используйте это как ссылку. должен помочь вам. - person Raghunandan; 20.05.2013
comment
эй, Рагунандан, твой код работает... я пытался внедрить его в мой, но он просто не будет работать... я думаю, проблема в том, что у меня есть другой адаптер, который создает сетку кнопок, и оттуда я добавляю прослушиватель onclick внутри этого слушатель, вызывающий ia.notifyDataSetChanged();.... (НЕ в методе onCreate)... может ли это быть проблемой??? - person ; 20.05.2013
comment
@ronanc да, вы можете найти представление по идентификатору и инициализировать представление в иерархии представлений, установленное для действия. Так что это не сработает. Это проблема. Имейте кнопку в onCreate(), а затем используйте вышеприведенное, тогда она должна работать - person Raghunandan; 20.05.2013
comment
эй, Рагунандан! :(... я переместил кнопку onClick на onCreate и угадайте, что ????? все еще без радости!!!!:).... вы можете увидеть мой класс в редактировании основного вопроса .. .не могу понять это...посмотрите на другие посты и может показаться, что вы нашли проблему :( - person ; 20.05.2013
comment
@ronanc посмотрит, дай мне пару минут - person Raghunandan; 20.05.2013
comment
@ronanc у вас есть два адаптера, я предлагаю вам отображать их отдельно на разных экранах. - person Raghunandan; 20.05.2013