2016-03-08 1 views
3

Я новичок в разработке Android и в настоящее время изучаю, как создавать диаграммы с надеждой на окончательное подключение к БД и создание динамических диаграмм. Я использовал пример из диаграмм MPAndroid GitHub (https://github.com/PhilJay/MPAndroidChart/) и пытаюсь манипулировать им в соответствии с моими требованиями.MP Android Chart - Как установить количество баров по умолчанию, отображаемое в представлении BarGraph?

Прямо сейчас моя диаграмма имеет ось x (дни) и ось y (галлоны).

Для простоты я создал массив строк «Day1» до «Day30», который я использую как мои значения X. Значения Y - это случайное число (просто чтобы увидеть различные размеры бара).

Сейчас: Мой график показывает все 30 дней со случайными Y значениями и я могу увеличивать и уменьшать масштаб, а также прокрутку влево или вправо при увеличении

Что я хотел бы:. Когда мой граф построен, я бы хотел, чтобы по умолчанию для графика отображалось только 7 дней (например, «День5» через «День11»), но все же можно прокручивать влево или вправо на графике, чтобы просмотреть другие дни 1-30 , Кроме того, я хотел бы иметь возможность уменьшить с 7 дней до максимум 30 дней или увеличить масштаб, чтобы просмотреть как минимум 3 дня.

Это мой файл java в настоящее время. Я знаю его неаккуратно на данный момент, Im обучения

public class ConsumptionActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener, OnChartValueSelectedListener, OnSeekBarChangeListener { 


    protected BarChart mChart; 
    private SeekBar mSeekBarX, mSeekBarY; 
    private TextView tvX, tvY; 

    private Typeface mTf; 
    protected String[] mDays = new String[] { 
      "Day 1","Day 2","Day 3","Day 4","Day 5","Day 6","Day 7","Day 8","Day 9","Day 10","Day 11","Day 12","Day 13","Day 14","Day 15", 
      "Day 16","Day 17","Day 18","Day 19","Day 20","Day 21","Day 22","Day 23","Day 24","Day 25","Day 26","Day 27","Day 28","Day 29","Day 30"}; 



    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_consumption); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 


     setSupportActionBar(toolbar); 



     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 

     Intent intent = getIntent(); 
     LoginAuthentification loggedIn = (LoginAuthentification) intent.getExtras().getSerializable("LoginClass"); 


     Spinner spinner = (Spinner) findViewById(R.id.accountDropdown); 

     SpinnerAdapter snprAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, loggedIn.getAccountList()); 


     spinner.setAdapter(snprAdapter); 

// Create an ArrayAdapter using the string array and a default spinner layout 
     /*ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, 
       R.array.test, android.R.layout.simple_spinner_item); 
// Specify the layout to use when the list of choices appears 
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
// Apply the adapter to the spinner 
     spinner.setAdapter(adapter);*/ 
     spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
       // An item was selected. You can retrieve the selected item using 
       // parent.getItemAtPosition(pos) 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> parent) { 
       // Another interface callback 
      } 
     }); 

     ObjectMapper mapper = new ObjectMapper(); 
     APICalls accountInfo = new APICalls(); 
     AccountDetails accountInUse = new AccountDetails(); 


     try { 
      accountInUse = mapper.readValue(String.valueOf(accountInfo.AccountDetails(loggedIn.getToken(),loggedIn.getAccountList().get(0))), AccountDetails.class); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 


     /*tvX = (TextView) findViewById(R.id.tvXMax); 
     tvY = (TextView) findViewById(R.id.tvYMax); 

     mSeekBarX = (SeekBar) findViewById(R.id.seekBar1); 
     mSeekBarY = (SeekBar) findViewById(R.id.seekBar2);*/ 

     mChart = (BarChart) findViewById(R.id.chart1); 
     mChart.setOnChartValueSelectedListener(this); 

     mChart.setDrawBarShadow(false); 
     mChart.setDrawValueAboveBar(true); 

     mChart.setDescription("Water Consumption Details"); 
     mChart.animateXY(8000, 8000); 
     // if more than 60 entries are displayed in the chart, no values will be 
     // drawn 
     mChart.setMaxVisibleValueCount(60); 

     // scaling can now only be done on x- and y-axis separately 
     mChart.setPinchZoom(false); 

     mChart.setDrawGridBackground(true); 
     // mChart.setDrawYLabels(false); 

     mTf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf"); 

     XAxis xAxis = mChart.getXAxis(); 
     xAxis.setPosition(XAxisPosition.BOTTOM); 
     xAxis.setTypeface(mTf); 
     xAxis.setDrawGridLines(false); 
     xAxis.setSpaceBetweenLabels(2); 


     YAxisValueFormatter custom = new MyYAxisValueFormatter(); 

     YAxis leftAxis = mChart.getAxisLeft(); 
     leftAxis.setTypeface(mTf); 
     leftAxis.setLabelCount(8, false); 
     leftAxis.setValueFormatter(custom); 
     leftAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART); 
     leftAxis.setSpaceTop(15f); 
     leftAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true) 

     YAxis rightAxis = mChart.getAxisRight(); 
     rightAxis.setDrawGridLines(false); 
     rightAxis.setTypeface(mTf); 
     rightAxis.setLabelCount(8, false); 
     rightAxis.setValueFormatter(custom); 
     rightAxis.setSpaceTop(15f); 
     rightAxis.setAxisMinValue(0f); // this replaces setStartAtZero(true) 

     Legend l = mChart.getLegend(); 
     l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT); 
     l.setForm(Legend.LegendForm.SQUARE); 
     l.setFormSize(9f); 
     l.setTextSize(11f); 
     l.setXEntrySpace(4f); 
     //l.setExtra(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc", 
     //"def", "ghj", "ikl", "mno" }); 
     //l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc", 
     //"def", "ghj", "ikl", "mno" }); 


     setData(30, 50); 

     // setting data 
     /* mSeekBarY.setProgress(50); 
     mSeekBarX.setProgress(12); 

     mSeekBarY.setOnSeekBarChangeListener(this); 
     mSeekBarX.setOnSeekBarChangeListener(this);*/ 

     // mChart.setDrawLegend(false); 




/* 
     APICalls callsForAll = new APICalls(); 
     try { 
      callsForAll.AccountDetails(token.get(0),token.get(1)); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     final TextView nameView = (TextView) findViewById(R.id.name); 

*/ 
    } 




    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.consumption, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     // Handle navigation view item clicks here. 
     int id = item.getItemId(); 

     if (id == R.id.nav_Alerts) { 

     } else if (id == R.id.nav_settings) { 

     } 
      else if (id == R.id.nav_Logout){ 

      // LOGOUT LOGIC SHOULD GO HERE 
      android.os.Process.killProcess(android.os.Process.myPid()); 
      System.exit(1); 
     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

    @Override 
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 

    } 

    @Override 
    public void onStartTrackingTouch(SeekBar seekBar) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onStopTrackingTouch(SeekBar seekBar) { 
     // TODO Auto-generated method stub 

    } 

    private void setData(int count, float range) { 

     ArrayList<String> xVals = new ArrayList<String>(); 
     for (int i = 0; i < count; i++) { 
      xVals.add(mDays[i]); 
     } 

     ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>(); 

     for (int i = 0; i < count; i++) { 
      float mult = (range + 1); 
      float val = (float) (Math.random() * mult); 
      yVals1.add(new BarEntry(val, i)); 
     } 

     BarDataSet set1 = new BarDataSet(yVals1, "DataSet"); 
     set1.setBarSpacePercent(35f); 
     ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>(); 
     dataSets.add(set1); 
     set1.setColors(new int[]{R.color.neptuneOrange,R.color.colorPrimary}); 

     BarData data = new BarData(xVals, dataSets); 
     data.setValueTextSize(10f); 
     data.setValueTypeface(mTf); 

     mChart.setData(data); 
    } 

    @SuppressLint("NewApi") 
    @Override 
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) { 

     if (e == null) 
      return; 

     RectF bounds = mChart.getBarBounds((BarEntry) e); 
     PointF position = mChart.getPosition(e, AxisDependency.LEFT); 

     Log.i("bounds", bounds.toString()); 
     Log.i("position", position.toString()); 

     Log.i("x-index", 
       "low: " + mChart.getLowestVisibleXIndex() + ", high: " 
         + mChart.getHighestVisibleXIndex()); 
    } 

    public void onNothingSelected() { 
    }; 
} 
+0

Здесь вы найдете: https://github.com/PhilJay/MPAndroidChart/wiki/Modifying-the-Viewport Я тоже работаю с этой библиотекой. Я бы порекомендовал вам прочитать полную вики. – XxGoliathusxX

+0

Спасибо! Я смотрел на wiki и javadoc, но не знал, на что конкретно я должен смотреть. Я прочитаю и надеюсь, что все получится! – Bang

+0

@Bang у вас есть ответ? – KJEjava48

ответ

2

setMaxVisibleValueCount (кол-INT): Устанавливает количество максимальных видимых нарисованных ценностными меток на графике. Это влияет только на то, когда включен setDrawValues ​​(). Обратитесь к API

Смежные вопросы