实现原理:gridview通过baseadapter适配器,getview方法对应添加不同的布局来改变背景颜色
实现效果图:
(1)主界面布局
<GridView
android:id="@+id/gridViews"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:stretchMode="columnWidth" />
(2)单选项卡item布局
<?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">
<LinearLayout
android:layout_width="240dp"
android:layout_height="150dp"
android:layout_marginTop="10dp"
android:background="@android:color/holo_red_dark"
android:orientation="vertical">
<TextView
android:id="@+id/tv_tem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="湿度"
android:textColor="#000"
android:textSize="32sp" />
<TextView
android:id="@+id/tv_num"
android:layout_width="80dp"
android:layout_height="80dp"
android:gravity="center"
android:layout_marginLeft="100dp"
android:layout_marginTop="30dp"
android:background="@android:color/holo_blue_dark"
android:text="32" />
</LinearLayout>
</LinearLayout>
(3)在activity节目添加适配器和随机数数据,如果是网络请求的话,同理
public class GridActivity extends Activity {
private GridView gridView;
GridviewAdapter adapter;
private String[] enstrings = new String[] {"温度","湿度","co2","pm2.5","光照","道路状态"};
// private String[] ennums = new String[] {"32","80","567","324","58","456"};
double num1=50;
double num2=180;
float[] temps =new float[6];
Handler handler = new Handler();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridView = (GridView)findViewById(R.id.gridViews);
handler.postDelayed(new Runnable() {
@Override
public void run() {
try {
handler.postDelayed(this, 3000);
for (int i=0;i<6;i++){
temps[i]=(int)num1+(int)(Math.random()*(num2-num1));
}
Log.e("TAG","189---"+temps[1]);
GridviewAdapter adapter = new GridviewAdapter();
gridView.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 3000); //每隔1s执行
GridviewAdapter adapter = new GridviewAdapter();
gridView.setAdapter(adapter);
}
class GridviewAdapter extends BaseAdapter{
TextView tv_tem,tv_num;
@Override
public int getCount() {
return enstrings.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (temps[i] < 90){
view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.gridviewlight,null);
}else{
view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.gridview,null);
}
tv_tem = (TextView)view.findViewById(R.id.tv_tem);
tv_num = (TextView)view.findViewById(R.id.tv_num);
tv_tem.setText(enstrings[i]);
tv_num.setText(String.valueOf(temps[i]));
return view;
}
}
}
本文摘自 :https://blog.51cto.com/u