更新传递给适配器的列表对象以创建GridView

时间:2015-12-18 09:27:00

标签: android gridview android-arrayadapter

我正在尝试更新已传递给适配器的列表对象的内容,以便创建GridView。这是代码:

 public class GameActivity extends Activity {
List<String> nums;
GridView sudoku_grid;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_temp);
    sudoku_grid=(GridView)findViewById(R.id.sudoku_grid);
    nums= Arrays.asList("1","2","3","5","7","8","2","3","1","9","3","3","1");
    adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,nums);
    sudoku_grid.setAdapter(adapter);
}

    public void trial(View view)
    {
        Runnable r=new Runnable() {
            @Override
            public void run() {
                nums.add("7");
                adapter.notifyDataSetChanged();
            }};
        new Thread(r).start();
    }
每次单击按钮时都会执行

trial()。一旦trial()中的线程启动,而不是更新的内容,它将导致启动上一个活动。谁能告诉我哪里出错?

2 个答案:

答案 0 :(得分:2)

您需要再次将nums对象传递给适配器。 创建class extends ArrayAdapter<String> 如下:

class MyArrayAdapter extends ArrayAdapter<String>{

    List<String> nums;

    public MyArrayAdapter(Context context,int itemID,List<String> nums){
        this.nums=nums;
    }

    @ovverride
    public int getCount() {
        return nums.size();
    }

    public void changeObjects(List<String> nums){
        this.nums=nums;
        this.notifyDataSetChanged();
    }

    public View getView(int position, View convertView, ViewGroup parent){
        //.... Implement own code
    }

}

如果有任何问题或疑问,请告诉我。

答案 1 :(得分:2)

我认为您无法在自己的主题中运行notifyDataSetChanged()。它需要在UI线程上运行。

尝试:

GameActivity.this.runOnUiThread(new Runnable() {
    ...

代替。