按下按钮后逐步绘制图表

时间:2018-09-08 15:51:49

标签: java android multithreading graph sine

嗨,我想在按下按钮后逐步在应用程序中绘制一个正弦波。问题是,结果出现在整个代码完成之后,而不是在循环的每次迭代之后。程序在每次迭代后都在等待,但是该图没有出现。我该怎么做才能显示产生此正弦波的过程?

package com.example.mroso.secondgraph.feature;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;



public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button b= (Button) findViewById(R.id.Button);
        final GraphView graph = (GraphView) findViewById(R.id.graph);
        final TextView t= (TextView) findViewById(R.id.Text);
        graph.getViewport().setXAxisBoundsManual(true);
        graph.getViewport().setMinX(0);
        graph.getViewport().setMaxX(100);
        graph.getViewport().setScrollable(true);
        graph.getViewport().setScalable(true);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                graph.removeAllSeries();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DataPoint[] pkt= new DataPoint[1];
                            for (int i = 0; i < 100; i++) {
                                DataPoint[] punkty = new DataPoint[i + 1];
                                if (i==0){
                                    punkty[i]=new DataPoint(i, Math.sin(i * Math.PI / 9));
                                }
                                else {
                                    for (int j = 0; j < i ; j++)
                                        punkty[j] = pkt[j];
                                }
                                punkty[i]=new DataPoint(i, Math.sin(i * Math.PI / 9));
                                ((TextView) findViewById(R.id.Text)).setText(String.valueOf(punkty[i].getY()));
                                LineGraphSeries<DataPoint> series = new LineGraphSeries<>(punkty);
                                graph.addSeries(series);
                                try {
                                    Thread.sleep(50);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                pkt= new DataPoint[i+1];
                                pkt=punkty;
                            }
                        }
                    });
                }
        });
    }
}

0 个答案:

没有答案