如何刷新Android GridView?

时间:2014-05-17 16:56:20

标签: android gridview refresh

我在Android中编写代码,每2分钟刷新一次Gridview。我在网上搜索了很多,但我找不到任何特定的技术来做这件事。

Java代码

MainActivity.java

package com.example.mycustomgridrefresh;

import java.util.ArrayList;

import android.os.Bundle;
import android.widget.GridView;
import android.app.Activity;

public class MainActivity extends Activity
{     

GridView gd;

MyGrid mg;

ArrayList<String> abc;

@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    gd = (GridView)findViewById(R.id.gd);

    abc = new ArrayList<String>();

    for(int i=0;i<100;i++)
    {
        abc.add(String.valueOf(i));

    }

    mg = new MyGrid(this,this,abc);

    gd.setAdapter(mg);

}}

MyGrid.java

package com.example.mycustomgridrefresh;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

 public class MyGrid extends BaseAdapter
 {

ArrayList<String> abc;

Activity activity;

public MyGrid(Activity activity , Context cont,ArrayList<String> abc)
{

    super();

    this.abc = abc;

    this.activity = activity;

}

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

@Override
public Object getItem(int arg0) 
{

     return abc.get(arg0);
}

@Override
public long getItemId(int arg0) 
{

    return 0;


}

public class ViewHolder
{

    public TextView txt;

}


@Override
public View getView(int arg0, View arg1, ViewGroup arg2) 
{

    ViewHolder view;

    LayoutInflater inflator = activity.getLayoutInflater();

    if(arg1==null)
    {

        view = new ViewHolder();

        arg1 = inflator.inflate(R.layout.mygrid, null);

        view.txt = (TextView) arg1.findViewById(R.id.txt);

        arg1.setTag(view);

    }
    else
    {

        view = (ViewHolder) arg1.getTag();

    }

    view.txt.setText(abc.get(arg0));

    return arg1;

}


}

以上网格打印100个数字是10行&amp;列。我想每2分钟更改一次网格单元格的值。该值应更改为+1。

请建议我一些好的解决方案。

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

刷新您需要在MyGrid中调用的值:

notifyDataSetChanged() 

每2分钟做一次任务你需要创建其他线程,如下所示:

public void startRunnable(){
   Runnable r = new Runnable() {        
        @Override
        public void run() {
         while(needToRefresh){
            //add one...
            this.notifyDataSetChanged();
            Thread.sleep(2000);
         }
    }
    };

    this.activity.runOnUiThread(r);
}

请勿忘记停止needToRefresh条件onPauseonStop

编辑:因为需要在UI线程中调用notifyDataSetChanged(),所以需要使用this.activity.runOnUiThread调用runnable 见那里:How to use notifyDataSetChanged() in thread