通过Handler实现自动添加HelloCharts数据和自动跳转Fragment


写在前面

由于本人初学阶段,写这篇博客是总结所学的知识点,为后面的进阶打好基础

有任何关于代码和表述问题,欢迎评论区指出

楼主最近老师要求做三个Fragment在一个MainActivity中实现自动跳转,每个Fragment中使用流行的图表开源APIHelloCharts,每个HelloCharts都要自动添加数据,并显示当前的温度,湿度或PM值!

三个Fragment分别是

  • 温度曲线图
  • 湿度曲线图
  • PM值曲线图

注意:楼主所用IDE是Eclipse ,API21 ,虚拟机屏幕大小为1280dp*720dp

HelloCharts需要导入jar包,下载途径大家自己可以去找

所用到的颜色都可以在颜色对照表中参考到

话不多说开始上代码

1. 界面布局

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"
    tools:context="com.zhuang.hellocharts.MainActivity" >

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

        <FrameLayout
            android:id="@+id/frameLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" >
        </FrameLayout>
    </LinearLayout>

</RelativeLayout>

fragment_humidity.xml

<?xml version="1.0" encoding="utf-8"?>
<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:background="#90d7ec"
    tools:context="com.zhuang.hellocharts.HumidityFragment" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="35dp"
            android:layout_marginTop="10dp"
            android:drawableLeft="@drawable/humidity_off"
            android:text="Humidity实时湿度数据曲线图"
            android:textColor="#ed1941"
            android:textSize="25sp"
            android:textStyle="bold" />
    </LinearLayout>

    <lecho.lib.hellocharts.view.LineChartView
        android:id="@+id/humLineChartView"
        android:layout_width="900dp"
        android:layout_height="500dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="#fab27b" />

    <TextView
        android:id="@+id/textViewhum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/linearLayout1"
        android:layout_marginLeft="272dp"
        android:layout_toRightOf="@+id/linearLayout1"
        android:text="TextView"
        android:textColor="#ed1941"
        android:textSize="16sp"
        android:textStyle="bold" />

</RelativeLayout>

fragment_pm.xml

<?xml version="1.0" encoding="utf-8"?>
<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:background="#ffe600"
    tools:context="com.zhuang.hellocharts.PMFragment" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="35dp"
            android:layout_marginTop="10dp"
            android:drawableLeft="@drawable/pm_off"
            android:text="PM2.5实时PM数据曲线图"
            android:textColor="#ed1941"
            android:textSize="20sp"
            android:textStyle="bold" />
    </LinearLayout>

    <lecho.lib.hellocharts.view.LineChartView
        android:id="@+id/pmLineChartView"
        android:layout_width="900dp"
        android:layout_height="500dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="#411445" />

    <TextView
        android:id="@+id/textViewpm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/linearLayout1"
        android:layout_marginLeft="272dp"
        android:layout_toRightOf="@+id/linearLayout1"
        android:text="TextView"
        android:textColor="#ed1941"
        android:textSize="16sp"
        android:textStyle="bold" />

</RelativeLayout>

fragment_temperature.xml

<?xml version="1.0" encoding="utf-8"?>
<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:background="#444693"
    tools:context="com.zhuang.hellocharts.TemperatureFragment" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="35dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/temp_off"
            android:text="Temperature实时温度数据曲线图"
            android:textColor="#ed1941"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="310dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:text="温度"
            android:textColor="#ed1941"
            android:textSize="16sp"
            android:textStyle="bold" />
    </LinearLayout>

    <lecho.lib.hellocharts.view.LineChartView
        android:id="@+id/tempLineChartView"
        android:layout_width="900dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="#b4532a" />

</RelativeLayout>

2. Activity实现功能

MainActivity

  • 初始化Fragment

  • 这个界面将Fragment添加到FrameLayout

  • 实现通过HandlerThread实现界面的自动切换,加几个if判断即可,想要自动,Handler可不能少

  • Handler发消息,根据接收到的消息显示指定的Fragment

package com.zhuang.hellocharts;

import com.czie.assessment.R;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView tempTextView, humTextView, pmTextView;
	int count = 1;
	TemperatureFragment temperatureFragment;
	HumidityFragment humidityFragment;
	PMFragment pmFragment;
	FragmentManager fragmentManager = getFragmentManager();
	Fragment curFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initFragment();
		showDifferentCharts();
	}
	//将Fragment添加到指定布局
	private void initFragment() {
		// TODO Auto-generated method stub
		temperatureFragment = new TemperatureFragment();
		humidityFragment = new HumidityFragment();
		pmFragment = new PMFragment();

		FragmentTransaction transaction = fragmentManager.beginTransaction();
		transaction.add(R.id.frameLayout, temperatureFragment);
		transaction.add(R.id.frameLayout, humidityFragment);
		transaction.add(R.id.frameLayout, pmFragment);
		showFragment(temperatureFragment);
		transaction.commit();
	}

	public void showFragment(Fragment fragment) {
		if (curFragment == fragment) {
			return;
		}
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		transaction.hide(temperatureFragment);
		transaction.hide(humidityFragment);
		transaction.hide(pmFragment);
		transaction.show(fragment);
		transaction.commit();
		curFragment = fragment;
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				showFragment(temperatureFragment);
				break;
			case 2:
				showFragment(humidityFragment);
				break;
			case 3:
				showFragment(pmFragment);
				break;
			}
		}
	};

	// 来回切换
	public void showDifferentCharts() {
		new Thread() {
			@Override
			public void run() {

				while (true) {
					if (count == 4) {
						count = 0;
					}
					try {
						sleep(5000);
						handler.sendEmptyMessage(count);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					count++;
				}
			}
		}.start();
	}

}

3. 实现图表自动添加数据

  • HelloCharts有关方法参考下列代码注释,很详细

  • 首先肯定不用想,肯定用HandlerThread来实现自动添加数据

  • 用到集合和数组用来存放数据

分析下关键代码 以一个Fragment为例,其余都一样参考即可

  • 该方法就可以是X轴上的数据是以时间通过处理显示,不会重复
public String[] getXData(int historysecond) {
		String historyDates[] = new String[historysecond];
		for (int i = 0; i < historysecond; i++) {
			// 获取时间
			Calendar calendar = Calendar.getInstance();
			// 获取秒数
			int second = calendar.get(calendar.SECOND);
			// 获取分钟
			int mins = calendar.get(calendar.MINUTE);
			historyDates[i] = String.format("%02d", mins) + ":"
					+ String.format("%02d", second);
		}
		return historyDates;
	}
  • 该方法就是可以一直显示当前的温度,和保证集合的个数不会超过7
public void readSensorData() {
		new Thread() {
			public void run() {
				super.run();
				while (true) {

					for (int i = 0; i < valus.length; i++) {
						if (flag != 0) {
							flag = valus[i];
						} else {
							flag = valus[i];
						}
						axisTimeValues = getXData(8);
						sensorPointValuesList.add(valus[i]);

						if (sensorPointValuesList.size() > 7) {
							sensorPointValuesList.remove(0);
						}
						// sensorPointValuesList.add(valus[i]);
						handler.sendEmptyMessage(0);
						try {
							sleep(1000);

						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			};
		}.start();
	}
  • Handler里调用该方法,每次显示完数据后,就要清空一次X轴和Y轴的数据,不断往集合里添加数据
public void showCharts() {
		mAxisValues.clear();
		mPointValues.clear();
		getAxisPoints();
		getAxisXLables();
		initLineChart("时间", "湿度");
	}

HumidityFragment

package com.zhuang.hellocharts;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.czie.assessment.R;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class HumidityFragment extends Fragment {
	private LineChartView lineChart;

	// x轴
	String axisTimeValues[] = new String[7];
	// y轴
	List<Integer> sensorPointValuesList = new ArrayList<Integer>();
	int[] valus = { 10, 15, 25, 20, 5, 15, 0 };
	int flag = 0;
	private TextView textViewhum;
	private List<PointValue> mPointValues = new ArrayList<PointValue>();
	// 存放x坐标轴上的数据的集合
	private List<AxisValue> mAxisValues = new ArrayList<AxisValue>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_humidity, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lineChart = (LineChartView) getActivity().findViewById(
				R.id.humLineChartView);
		textViewhum = (TextView) getActivity().findViewById(R.id.textViewhum);
		readSensorData();
	}

	public void readSensorData() {
		new Thread() {
			public void run() {
				super.run();
				while (true) {

					for (int i = 0; i < valus.length; i++) {
						if (flag != 0) {
							flag = valus[i];
						} else {
							flag = valus[i];
						}
						axisTimeValues = getXData(8);
						sensorPointValuesList.add(valus[i]);

						if (sensorPointValuesList.size() > 7) {
							sensorPointValuesList.remove(0);
						}
						// sensorPointValuesList.add(valus[i]);
						handler.sendEmptyMessage(0);
						try {
							sleep(1000);

						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			};
		}.start();
	}

	// x数据的获取
	public String[] getXData(int historysecond) {
		String historyDates[] = new String[historysecond];
		for (int i = 0; i < historysecond; i++) {
			// 获取时间
			Calendar calendar = Calendar.getInstance();
			// 获取秒数
			int second = calendar.get(calendar.SECOND);
			// 获取分钟
			int mins = calendar.get(calendar.MINUTE);
			historyDates[i] = String.format("%02d", mins) + ":"
					+ String.format("%02d", second);
		}
		return historyDates;
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			showCharts();
			textViewhum.setText("当前湿度:" + flag + "RH%");

		};
	};

	public void showCharts() {
		mAxisValues.clear();
		mPointValues.clear();
		getAxisPoints();
		getAxisXLables();
		initLineChart("时间", "湿度");
	}

	private void initLineChart(String xName, String yName) {
		// TODO Auto-generated method stub
		Line line = new Line(mPointValues)
				.setColor(Color.parseColor("#ef5b9c")); // 折线的颜色(橙色)
		List<Line> lines = new ArrayList<Line>();
		line.setShape(ValueShape.DIAMOND); // 折线图上每个数据的形状
		line.setCubic(true); // 曲线是否平滑,即是曲线还是折线
		line.setFilled(false); // 是否填充曲线的面积
		line.setHasLabels(true); // 曲线的数据坐标是否加上备注
		line.setHasLines(true); // 是否用线显示
		line.setHasPoints(true); // 是否显示圆点
		lines.add(line);
		LineChartData data = new LineChartData();
		data.setLines(lines);

		// 坐标轴
		Axis axisX = new Axis(); // x轴
		axisX.setName(xName);
		axisX.setHasTiltedLabels(true); // x轴字体是斜还是直
		axisX.setTextColor(Color.WHITE); // 字体颜色
		axisX.setTextSize(10); // 字体大小
		axisX.setMaxLabelChars(10); // 最多几个x轴坐标
		axisX.setValues(mAxisValues); // 填充x轴的坐标名称
		data.setAxisXBottom(axisX); // x轴在底部
		axisX.setHasLines(true); // x轴分割线

		Axis axisY = new Axis(); // y轴
		axisY.setName(yName); // y轴标注
		axisY.setTextSize(10);
		data.setAxisYLeft(axisY); // y轴在左边
		// 设置行为属性,支持缩放、滑动和平移
		lineChart.setInteractive(true);
		lineChart.setZoomType(ZoomType.HORIZONTAL);
		lineChart.setMaxZoom((float) 2); // 最大方法比例
		lineChart.setContainerScrollEnabled(true,
				ContainerScrollType.HORIZONTAL);
		lineChart.setLineChartData(data);
		lineChart.setVisibility(View.VISIBLE);
		Viewport v = new Viewport(lineChart.getMaximumViewport());
		// y轴最高值
		v.top = 100;
		// y轴最低值
		v.bottom = 0;
		lineChart.setMaximumViewport(v);
		v.left = 0;
		v.right = 7;
		lineChart.setCurrentViewport(v);
	}

	private void getAxisXLables() {
		// TODO Auto-generated method stub
		for (int i = 0; i < axisTimeValues.length; i++) {
			mAxisValues.add(new AxisValue(i).setLabel(axisTimeValues[i]));
		}
	}

	private void getAxisPoints() {
		for (int i = 0; i < sensorPointValuesList.size(); i++) {
			mPointValues.add(new PointValue(i, sensorPointValuesList.get(i)));
		}
	}
}

PMFragment

package com.zhuang.hellocharts;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.czie.assessment.R;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class PMFragment extends Fragment {

	private LineChartView lineChart;

	// x轴
	String axisTimeValues[] = new String[7];
	// y轴
	List<Integer> sensorPointValuesList = new ArrayList<Integer>();
	int[] valus = { 20, 45, 10, 50, 60, 24, 36 };
	int flag = 0;
	private TextView textViewpm;
	private List<PointValue> mPointValues = new ArrayList<PointValue>();
	// 存放x坐标轴上的数据的集合
	private List<AxisValue> mAxisValues = new ArrayList<AxisValue>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_pm, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lineChart = (LineChartView) getActivity().findViewById(
				R.id.pmLineChartView);
		textViewpm = (TextView) getActivity().findViewById(R.id.textViewpm);
		readSensorData();
	}

	public void readSensorData() {
		new Thread() {
			public void run() {
				super.run();
				while (true) {

					for (int i = 0; i < valus.length; i++) {
						if (flag != 0) {
							flag = valus[i];
						} else {
							flag = valus[i];
						}
						axisTimeValues = getXData(8);
						sensorPointValuesList.add(valus[i]);

						if (sensorPointValuesList.size() > 7) {
							sensorPointValuesList.remove(0);
						}
						// sensorPointValuesList.add(valus[i]);
						handler.sendEmptyMessage(0);
						try {
							sleep(1000);

						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			};
		}.start();
	}

	// x数据的获取
	public String[] getXData(int historysecond) {
		String historyDates[] = new String[historysecond];
		for (int i = 0; i < historysecond; i++) {
			// 获取时间
			Calendar calendar = Calendar.getInstance();
			// 获取秒数
			int second = calendar.get(calendar.SECOND);
			// 获取分钟
			int mins = calendar.get(calendar.MINUTE);
			historyDates[i] = String.format("%02d", mins) + ":"
					+ String.format("%02d", second);
		}
		return historyDates;
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			showCharts();
			textViewpm.setText("当前PM值:" + flag + "ug/m3");

		};
	};

	public void showCharts() {
		mAxisValues.clear();
		mPointValues.clear();
		getAxisPoints();
		getAxisXLables();
		initLineChart("时间", "PM");
	}

	private void initLineChart(String xName, String yName) {
		// TODO Auto-generated method stub
		Line line = new Line(mPointValues)
				.setColor(Color.parseColor("#6d8346")); // 折线的颜色(橙色)
		List<Line> lines = new ArrayList<Line>();
		line.setShape(ValueShape.CIRCLE); // 折线图上每个数据的形状
		line.setCubic(true); // 曲线是否平滑,即是曲线还是折线
		line.setFilled(false); // 是否填充曲线的面积
		line.setHasLabels(true); // 曲线的数据坐标是否加上备注
		line.setHasLines(true); // 是否用线显示
		line.setHasPoints(true); // 是否显示圆点
		lines.add(line);
		LineChartData data = new LineChartData();
		data.setLines(lines);

		// 坐标轴
		Axis axisX = new Axis(); // x轴
		axisX.setName(xName);
		axisX.setHasTiltedLabels(true); // x轴字体是斜还是直
		axisX.setTextColor(Color.WHITE); // 字体颜色
		axisX.setTextSize(10); // 字体大小
		axisX.setMaxLabelChars(10); // 最多几个x轴坐标
		axisX.setValues(mAxisValues); // 填充x轴的坐标名称
		data.setAxisXBottom(axisX); // x轴在底部
		axisX.setHasLines(true); // x轴分割线

		Axis axisY = new Axis(); // y轴
		axisY.setName(yName); // y轴标注
		axisY.setTextSize(10);
		data.setAxisYLeft(axisY); // y轴在左边
		// 设置行为属性,支持缩放、滑动和平移
		lineChart.setInteractive(true);
		lineChart.setZoomType(ZoomType.HORIZONTAL);
		lineChart.setMaxZoom((float) 2); // 最大方法比例
		lineChart.setContainerScrollEnabled(true,
				ContainerScrollType.HORIZONTAL);
		lineChart.setLineChartData(data);
		lineChart.setVisibility(View.VISIBLE);
		Viewport v = new Viewport(lineChart.getMaximumViewport());
		// y轴最高值
		v.top = 100;
		// y轴最低值
		v.bottom = 0;
		lineChart.setMaximumViewport(v);
		v.left = 0;
		v.right = 7;
		lineChart.setCurrentViewport(v);
	}

	private void getAxisXLables() {
		// TODO Auto-generated method stub
		for (int i = 0; i < axisTimeValues.length; i++) {
			mAxisValues.add(new AxisValue(i).setLabel(axisTimeValues[i]));
		}
	}

	private void getAxisPoints() {
		for (int i = 0; i < sensorPointValuesList.size(); i++) {
			mPointValues.add(new PointValue(i, sensorPointValuesList.get(i)));
		}
	}
}

TemperatureFragment

package com.zhuang.hellocharts;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.czie.assessment.R;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TemperatureFragment extends Fragment {

	private LineChartView lineChart;

	// x轴
	String axisTimeValues[] = new String[7];
	// y轴
	List<Integer> sensorPointValuesList = new ArrayList<Integer>();
	int[] valus = { 50, 27, 37, 47, 27, 45, 78 };

	private List<PointValue> mPointValues = new ArrayList<PointValue>();
	// 存放x坐标轴上的数据的集合
	private List<AxisValue> mAxisValues = new ArrayList<AxisValue>();
	int flag = 0;
	private TextView textView3;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater
				.inflate(R.layout.fragment_temperature, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lineChart = (LineChartView) getActivity().findViewById(
				R.id.tempLineChartView);
		textView3 = (TextView) getActivity().findViewById(R.id.textView3);
		readSensorData();
	}

	public void readSensorData() {
		new Thread() {
			public void run() {
				super.run();
				while (true) {

					for (int i = 0; i < valus.length; i++) {
						if (flag != 0) {
							flag = valus[i];
						} else {
							flag = valus[i];
						}
						axisTimeValues = getXData(8);
						sensorPointValuesList.add(valus[i]);

						if (sensorPointValuesList.size() > 7) {
							sensorPointValuesList.remove(0);
						}
						// sensorPointValuesList.add(valus[i]);

						handler.sendEmptyMessage(0);
						try {
							sleep(1000);

						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			};
		}.start();
	}

	// x数据的获取
	public String[] getXData(int historysecond) {
		String historyDates[] = new String[historysecond];
		for (int i = 0; i < historysecond; i++) {
			// 获取时间
			Calendar calendar = Calendar.getInstance();
			// 获取秒数
			int second = calendar.get(calendar.SECOND);
			// 获取分钟
			int mins = calendar.get(calendar.MINUTE);
			historyDates[i] = String.format("%02d", mins) + ":"
					+ String.format("%02d", second);
		}
		return historyDates;
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			showCharts();
			textView3.setText("当前温度:" + flag + "℃");

		};
	};

	public void showCharts() {
		mAxisValues.clear();
		mPointValues.clear();
		getAxisPoints();
		getAxisXLables();
		initLineChart("时间", "温度");
	}

	private void initLineChart(String xName, String yName) {
		// TODO Auto-generated method stub
		Line line = new Line(mPointValues)
				.setColor(Color.parseColor("#d71345")); // 折线的颜色(红色)
		List<Line> lines = new ArrayList<Line>();
		line.setShape(ValueShape.SQUARE); // 折线图上每个数据的形状
		line.setCubic(true); // 曲线是否平滑,即是曲线还是折线
		line.setFilled(false); // 是否填充曲线的面积
		line.setHasLabels(true); // 曲线的数据坐标是否加上备注
		line.setHasLines(true); // 是否用线显示
		line.setHasPoints(true); // 是否显示圆点
		lines.add(line);
		LineChartData data = new LineChartData();
		data.setLines(lines);

		// 坐标轴
		Axis axisX = new Axis(); // x轴
		axisX.setName(xName);
		axisX.setHasTiltedLabels(true); // x轴字体是斜还是直
		axisX.setTextColor(Color.WHITE); // 字体颜色
		axisX.setTextSize(10); // 字体大小
		axisX.setMaxLabelChars(10); // 最多几个x轴坐标
		axisX.setValues(mAxisValues); // 填充x轴的坐标名称
		data.setAxisXBottom(axisX); // x轴在底部
		axisX.setHasLines(true); // x轴分割线

		Axis axisY = new Axis(); // y轴
		axisY.setName(yName); // y轴标注
		axisY.setTextSize(10);
		data.setAxisYLeft(axisY); // y轴在左边
		// 设置行为属性,支持缩放、滑动和平移
		lineChart.setInteractive(true);
		lineChart.setZoomType(ZoomType.HORIZONTAL);
		lineChart.setMaxZoom((float) 2); // 最大方法比例
		lineChart.setContainerScrollEnabled(true,
				ContainerScrollType.HORIZONTAL);
		lineChart.setLineChartData(data);
		lineChart.setVisibility(View.VISIBLE);
		Viewport v = new Viewport(lineChart.getMaximumViewport());
		// y轴最高值
		v.top = 100;
		// y轴最低值
		v.bottom = 0;
		lineChart.setMaximumViewport(v);
		v.left = 0;
		v.right = 7;
		lineChart.setCurrentViewport(v);
	}

	private void getAxisXLables() {
		// TODO Auto-generated method stub
		for (int i = 0; i < axisTimeValues.length; i++) {
			mAxisValues.add(new AxisValue(i).setLabel(axisTimeValues[i]));
		}
	}

	private void getAxisPoints() {
		for (int i = 0; i < sensorPointValuesList.size(); i++) {
			mPointValues.add(new PointValue(i, sensorPointValuesList.get(i)));
		}
	}
}

最后通过简单动图来看下效果
2Ja8eS.gif
总结

  • 布局做的有点简单😂,在实现功能的基础上再美化就更好了
  • 还有许多不足的地方仍需努力💪,比如代码优化,对Hellocharts熟练运用

写在最后

  • 有任何错误欢迎评论区指出,及时改正!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值