Android实现显示柱状图

本文介绍了两种在Android应用中实现柱状图的方法。第一种是通过加载本地H5页面并利用Echarts库来绘制柱状图,第二种是纯Java实现,通过自定义布局和控件来绘制柱状图。文章提供了详细的代码示例,包括数据模型、JS交互类、Activity布局和自定义控件等。
摘要由CSDN通过智能技术生成

当前实现方式有2种,一种是加载本地的H5界面,然后JS中配置相关的属性,Echars地址,但是这种方式,似乎水平方向加载出来的数量是有限的,无法左右滑动。也可参考他人的博客他人Echars实现。下面粘贴一下在下的相关代码。

第一种,本地加载H5

1、创建相关的javabean类

public class AccessData {

    private String companyName;

    private Integer left;

    private Integer right;

    AccessData(String companyName, Integer left, Integer right) {
        this.companyName = companyName;
        this.left = left;
        this.right = right;
    }

    public String getCompanyName() {
        return companyName;
    }

    public Integer getLeft() {
        return left;
    }

    public Integer getRight() {
        return right;
    }

    /**
     * 模拟获取数据
     *
     * @return 此处可按照自定义的数据类型
     */
    public static List<AccessData> getWeekData() {
        List<AccessData> list = new ArrayList<AccessData>(7);
        list.add(new AccessData("A公司", 4, 8));
        list.add(new AccessData("B公司", 7, 5));
        list.add(new AccessData("C公司", 14, 16));
        list.add(new AccessData("D公司", 3, 200));
        list.add(new AccessData("E公司", 6, 20));
        list.add(new AccessData("F公司", 16, 5));
        return list;
    }
}

 2、创建JS交互类

public class MyLineChart {

    private String TAG = "MyLineChart";

    Context mContext;
    List<AccessData> lineDatas;

    public MyLineChart(Context context, List<AccessData> datas) {
        this.mContext = context;
        // 获取数据
        this.lineDatas = datas;
    }

    // 将该方法暴露给JavaScript脚本调用
    @JavascriptInterface
    public String getLineChartOptions() {
        GsonOption option = (GsonOption) creatLineChartOptions();
//            Log.d(option.toString());
        return option.toString();
    }

    // 此函数主要是绘 Line 图
    @JavascriptInterface
    public Option creatLineChartOptions() {

        // 创建Option对象
        GsonOption option = new GsonOption();

        // 设置图标标题,并且居中显示
//        option.title().text("最近7天的访问量").x(X.center);

        // 设置图例
        option.legend()
                .data("11", "22")
                .x(X.left)
                .y(Y.top)
                .setOrient(Orient.vertical);
        option.legend().setTextStyle(new TextStyle().color("#fff"));

        // 设置y轴为值轴,并且不显示y轴,最大值设置500,最小值0
        option.yAxis(new ValueAxis()
//                .name("IP")
                .axisLine(new AxisLine()
                        .show(true)
                        .lineStyle(new LineStyle().width(1).color("#fff")))  //设置宽度、颜色
//                .max(25)   //设置竖直坐标最大值,这不设置最大的,竖直数量大的时候,自动变化
                .min(0)     //设置竖直坐标最小值
                .axisTick(new AxisTick().show(false)));   //设置左边是否突出来

        // 创建类目轴,并且不显示竖着的分割线 X轴
        CategoryAxis categoryAxis = new CategoryAxis()
                .splitLine(new SplitLine().show(false))
                .axisLine(new AxisLine().onZero(false).lineStyle(new LineStyle().color("#fff")))
                .axisTick(new AxisTick().show(false));  //设置下方是否突出来

        // 不显示表格边框,就是围着图标的方框
        option.grid().borderWidth(0);

        //设置柱状图的颜色
        option.color("#0000ff", "#00ff00");

        //这里面参数需要加,不然就不显示文字
        Bar bar = new Bar("11");
        Bar bar2 = new Bar("22");

        // 创建Line数据

        // 根据获取的数据赋值
        for (AccessData lineData : lineDatas) {

            // 增加类目,值为日期
            categoryAxis.data(lineData.getCompanyName());

            // 日期对应的数据
            Integer wuxiaoYundan = lineData.getRight();
            bar.data(wuxiaoYundan)
                    .barGap("0")
                    .label()
                    .normal(new Normal()
                            .formatter(wuxiaoYundan + "") //设置上方显示的数量
                            .show(true) //设置显示数量
                            .color("#fff")  //设置数量字的名称
                            .position(Position.top))
            ;    //设置显示的位置

            Integer youxiaoYundan = lineData.getLeft();
            bar2.data(youxiaoYundan)
                    .barGap("0")
                    .label()
                    .normal(new Normal()
                            .formatter(youxiaoYundan + "") //设置上方显示的数量
                            .show(true) //设置显示数量
                            .color("#fff")  //设置数量字的名称
                            .position(Position.top));    //设置显示的位置
        }

        // 设置数据
        option.series(bar, bar2);

        // 设置X轴为类目轴
        option.xAxis(categoryAxis);

        //设置右边的工具栏
//        option.toolbox().show(true).orient(Orient.horizontal).left(Y.bottom);

        //设置背景颜色
        option.backgroundColor("#000000");

        return option;
    }
}

3、创建相关的界面Activity

public class MyActivity extends AppCompatActivity {

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_echars);
        webView = (WebView) findViewById(R.id.webView);

        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportZoom(true);
        webSettings.setDisplayZoomControls(true);

        // 获取指定数据格式的数据,此处可以和外部交互
        List<AccessData> datas = AccessData.getWeekData();
        webView.addJavascriptInterface(new MyLineChart(this, datas), "myLine");

        webView.loadUrl("file:///android_asset/myechart.html");
        webView.setWebViewClient(new WebViewClient());
    }
}

4、创建本地的H5文件

在main文件夹下,创建assets文件夹,放入相关的文件,结构如下:


myechart.html相关代码如下:

<head>
    <meta charset="utf-8" />
    <style>
        <!-- Css 样式-->
        ...
    </style>
</head>
<!-- ECharts单文件引入 -->
<script src="js/echarts.common.min.js"></script>

<body>
<!-- 为 ECharts 准备一个具备大小(宽高)的 DOM -->
<div id="main" style="float: center; width: '100%';height: 380px; margin-left: '2%';margin-bottom: 35px"></div>
<script type="text/javascript">
        // 图表的加载区域
        var dom = document.getElementById('main');
        var myChart = echarts.init(dom);
        // 必须加JOSN.parse 转换数据类型
        var option = JSON.parse(myLine.getLineChartOptions());

        // 查询
        function loadChart() {
            myChart.clear();
            myChart.showLoading({
                text: '正在努力的读取数据中...'
            });
            myChart.setOption(option);
            myChart.hideLoading();

        };

        // 载入图表
        loadChart();
    </script>

</body>

5、js文件

可从上面参考博客中去下载吧。

然后好像差不多了。

第二种,是自己使用java编写实现的

现在做出相关的样子了,具体的柱状图左边显示的数值、柱状图的高度设置,需要根据自己数据进行设置。

1、布局文件如下

相关样式没有抽取,部分可抽取。

include_topbar:是自定义的顶部的导航栏。
<?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"
    android:background="@color/black"
    android:orientation="vertical">

    <include layout="@layout/include_topbar" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/size_50dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_zhuzhuangtu_yuefen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_centerHorizontal="true"
            android:background="@drawable/shape_rectangle_stroke_white_corners"
            android:gravity="center"
            android:paddingLeft="@dimen/size_20dp"
            android:paddingTop="@dimen/size_8dp"
            android:paddingRight="@dimen/size_20dp"
            android:paddingBottom="@dimen/size_8dp"
            android:text="1111"
            android:textColor="@color/white" />

        <TextView
            android:id="@+id/tv_zhuzhuangtu_shengfen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/size_10dp"
            android:background="@drawable/shape_rectangle_stroke_white_corners"
            android:drawableRight="@drawable/white_jiantou_xia"
            android:gravity="center"
            android:text="2222"
            android:paddingLeft="@dimen/size_20dp"
            android:paddingTop="@dimen/size_8dp"
            android:paddingRight="@dimen/size_20dp"
            android:paddingBottom="@dimen/size_8dp"
            android:textColor="@color/white" />

    </RelativeLayout>

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:padding="@dimen/size_10dp">

            <ImageView
                android:layout_width="@dimen/size_10dp"
                android:layout_height="@dimen/size_10dp"
                android:background="#0f0" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/size_20dp"
                android:textColor="@color/white" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingLeft="@dimen/size_10dp">

            <ImageView
                android:layout_width="@dimen/size_10dp"
                android:layout_height="@dimen/size_10dp"
                android:background="#00BCD4" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/size_20dp"
                android:textColor="@color/white" />

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="450dp"
        android:layout_marginTop="@dimen/size_10dp"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/zhuzhuangtu_vertical_height"
            android:orientation="horizontal">

            <!--            左边的数值-->
            <LinearLayout
                android:layout_width="@dimen/size_50dp"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_zhuzhuangtu_left_number_one"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:gravity="center_horizontal|top"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/tv_zhuzhuangtu_left_number_two"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:gravity="center_horizontal|top"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/tv_zhuzhuangtu_left_number_three"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:gravity="center_horizontal|top"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/tv_zhuzhuangtu_left_number_four"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:gravity="center_horizontal|top"
                    android:textColor="@color/white" />

                <TextView
                    android:id="@+id/tv_zhuzhuangtu_left_number_five"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:textColor="@color/white" />

            </LinearLayout>

            <!--            左边的竖直竖线-->
            <ImageView
                android:layout_width="1px"
                android:layout_height="@dimen/zhuzhuangtu_vertical_height"
                android:layout_gravity="bottom"
                android:background="@color/white" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <!--            柱状图具体的内容-->
                <SyncHorizontalScrollView
                    android:id="@+id/hoscroll_top_content"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/black">

                    <!--                柱状图中具体内容-->
                    <LinearLayout
                        android:id="@+id/ll_zhuzhuangtu_top_content_container"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:gravity="bottom"
                        android:orientation="horizontal">

                    </LinearLayout>

                </SyncHorizontalScrollView>

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="1px"
                    android:background="@color/white" />

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="1px"
                    android:layout_marginTop="100dp"
                    android:background="@color/white" />

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="1px"
                    android:layout_marginTop="@dimen/size_200dp"
                    android:background="@color/white" />

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="1px"
                    android:layout_marginTop="300dp"
                    android:background="@color/white" />

            </RelativeLayout>

        </LinearLayout>

        <!--        下方的水平横线-->
        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:layout_marginLeft="@dimen/size_50dp"
            android:background="@color/white" />

        <!--        下方的具体的内容-->
        <SyncHorizontalScrollView
            android:id="@+id/hoscroll_bottom_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="@dimen/size_50dp">

            <LinearLayout
                android:id="@+id/ll_zhuzhuangtu_bottom_item_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="horizontal">

            </LinearLayout>

        </SyncHorizontalScrollView>

    </LinearLayout>

</LinearLayout>

2、布局文件中自定义控件如下

public class SyncHorizontalScrollView extends HorizontalScrollView {

    private View mView;

    public SyncHorizontalScrollView(Context context) {
        super(context);
    }

    public SyncHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SyncHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        //这是上方的水平标题与下方的水平内容进行绑定
        if (mView != null) {
            mView.scrollTo(l, t);
        }
    }

    public void setScrollView(View view) {
        mView = view;
    }

}

3、相关的Activity

public class ZhuzhuangtuActivity extends BaseActivity {

    @BindView(R.id.view_top_status_bar)
    View viewTopStatusBar;
    @BindView(R.id.ll_finish_activity)
    LinearLayout llFinishActivity;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.tv_topbar_right)
    TextView tvTopbarRight;
    @BindView(R.id.iv_topbar_right)
    ImageView ivTopbarRight;
    @BindView(R.id.ll_right_setting)
    LinearLayout llRightSetting;
    @BindView(R.id.rl_title_container)
    RelativeLayout rlTitleContainer;
    @BindView(R.id.hoscroll_top_content)
    SyncHorizontalScrollView hoscrollTopContent;
    @BindView(R.id.hoscroll_bottom_name)
    SyncHorizontalScrollView hoscrollBottomName;
    @BindView(R.id.tv_zhuzhuangtu_yuefen)
    TextView tvZhuzhuangtuYuefen;
    @BindView(R.id.tv_zhuzhuangtu_shengfen)
    TextView tvZhuzhuangtuShengfen;
    @BindView(R.id.tv_zhuzhuangtu_left_number_one)
    TextView tvZhuzhuangtuLeftNumberOne;
    @BindView(R.id.tv_zhuzhuangtu_left_number_two)
    TextView tvZhuzhuangtuLeftNumberTwo;
    @BindView(R.id.tv_zhuzhuangtu_left_number_three)
    TextView tvZhuzhuangtuLeftNumberThree;
    @BindView(R.id.tv_zhuzhuangtu_left_number_four)
    TextView tvZhuzhuangtuLeftNumberFour;
    @BindView(R.id.tv_zhuzhuangtu_left_number_five)
    TextView tvZhuzhuangtuLeftNumberFive;
    @BindView(R.id.ll_zhuzhuangtu_top_content_container)
    LinearLayout llZhuzhuangtuTopContentContainer;
    @BindView(R.id.ll_zhuzhuangtu_bottom_item_container)
    LinearLayout llZhuzhuangtuBottomItemContainer;

    @Override
    protected void mineInitData() {

        hoscrollBottomName.setScrollView(hoscrollTopContent);
        hoscrollTopContent.setScrollView(hoscrollBottomName);

        tvZhuzhuangtuLeftNumberOne.setText(400 + "");
        tvZhuzhuangtuLeftNumberTwo.setText(300 + "");
        tvZhuzhuangtuLeftNumberThree.setText(200 + "");
        tvZhuzhuangtuLeftNumberFour.setText(100 + "");
        tvZhuzhuangtuLeftNumberFive.setText(0 + "");

        ZhuzhuangTuContentView contentView = null;
        ZhuzhuangtuBottomTextview textview = null;

        for (int i = 0; i < 10; i++) {

            //设置上方的柱状图
            contentView = new ZhuzhuangTuContentView(this);
            contentView.setIvLeftHeight(100);
            contentView.setIvRightHeight(200);
            contentView.initView();
            llZhuzhuangtuTopContentContainer.addView(contentView);

            //设置下方的名称这些
            textview = new ZhuzhuangtuBottomTextview(this);

            if (i % 2 == 0) {
                textview.setBackgroundColor(Color.RED);
            } else {
                textview.setBackgroundColor(Color.YELLOW);
            }
            textview.setText("测试" + i);
            llZhuzhuangtuBottomItemContainer.addView(textview);

        }

    }

    @Override
    protected int mineSetContentViewId() {
        return R.layout.zhuzhuangtu_view;
    }

    @OnClick({R.id.ll_finish_activity, R.id.tv_zhuzhuangtu_yuefen, R.id.tv_zhuzhuangtu_shengfen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_finish_activity:
                finish();
                break;

            case R.id.tv_zhuzhuangtu_yuefen:
                //选择

                break;

            case R.id.tv_zhuzhuangtu_shengfen:
                //选择

                break;
        }
    }
}

4、柱状图底部的自定义的TextView

public class ZhuzhuangtuBottomTextview extends TextView {

    public ZhuzhuangtuBottomTextview(Context context) {
        this(context, null);
    }

    public ZhuzhuangtuBottomTextview(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZhuzhuangtuBottomTextview(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews();
    }

    private int bottomTextviewWidth = 70;

    private void initViews() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(UIUtils.dp2px(bottomTextviewWidth),
                ViewGroup.LayoutParams.WRAP_CONTENT);

        this.setMaxWidth(UIUtils.dp2px(bottomTextviewWidth));
        this.setLayoutParams(params);
        this.setGravity(Gravity.CENTER_HORIZONTAL);
        this.setTextColor(Color.WHITE);
    }
}
public class ZhuzhuangTuContentView extends LinearLayout {

    private Context mContext;

    public ZhuzhuangTuContentView(Context context) {
        this(context, null);
    }

    public ZhuzhuangTuContentView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZhuzhuangTuContentView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    private TextView tvLeft;
    private TextView tvRight;

    private ImageView ivLeft;
    private ImageView ivRight;

    private int ivLeftHeight;
    private int ivRightHeight;

    /**
     * 设置左边的柱状图的高度。直接传入dp值
     *
     * @param ivLeftHeight
     */
    public void setIvLeftHeight(int ivLeftHeight) {
        this.ivLeftHeight = ivLeftHeight;
    }

    /**
     * 设置右边的柱状图的高度。直接传入dp值
     *
     * @param ivRightHeight
     */
    public void setIvRightHeight(int ivRightHeight) {
        this.ivRightHeight = ivRightHeight;
    }

    private String tvLefuNum = 0 + "";
    private String tvRightNum = 0 + "";

    public void setTvLefuNum(String tvLefuNum) {
        this.tvLefuNum = tvLefuNum;
    }

    public void setTvRightNum(String tvRightNum) {
        this.tvRightNum = tvRightNum;
    }

    public void initView() {

        View view = View.inflate(mContext, R.layout.view_zhuzhuangtu, null);

        tvLeft = view.findViewById(R.id.tv_zhuzhuangtu_left);
        tvRight = view.findViewById(R.id.tv_zhuzhuangtu_right);

        ivLeft = view.findViewById(R.id.iv_zhuzhuangtu_left);
        ivRight = view.findViewById(R.id.iv_zhuzhuangtu_right);

        LinearLayout.LayoutParams leftParams = new LayoutParams(UIUtils.dp2px(25), UIUtils.dp2px(ivLeftHeight));
        ivLeft.setLayoutParams(leftParams);

        LinearLayout.LayoutParams rightParams = new LayoutParams(UIUtils.dp2px(25), UIUtils.dp2px(ivRightHeight));
        ivRight.setLayoutParams(rightParams);

        tvLeft.setText(tvLefuNum);
        tvRight.setText(tvRightNum);

        this.addView(view);

    }
}

好像差不多了吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值