質問編集履歴

1

viewModelを使った方法に変更

2021/12/13 13:36

投稿

luckyclock
luckyclock

スコア74

test CHANGED
File without changes
test CHANGED
@@ -12,13 +12,7 @@
12
12
 
13
13
  描画データがなくなってしまいます。
14
14
 
15
- なんとか描画データ継続し表示したいのすがどうすばよいでしょうか?
15
+ viewModel使っ書いてみましたが、タブ1→3→1再描画さません。
16
-
17
- なんとなくonSaveInstanceState使ってmchartを保持してoncreateで復元すればできるような気もす
18
-
19
- るのですが・・・
20
-
21
- あるいはタブ移動したときにフラグメントのインスタンスが破棄されないようにするとか?
22
16
 
23
17
 
24
18
 
@@ -26,35 +20,141 @@
26
20
 
27
21
  ```java
28
22
 
23
+
24
+
25
+ public class MainActivity extends AppCompatActivity {
26
+
27
+
28
+
29
+ private ActivityMainBinding binding;
30
+
31
+ private SectionsPagerAdapter sectionsPagerAdapter;
32
+
29
33
  @Override
30
34
 
31
35
  protected void onCreate(Bundle savedInstanceState) {
32
36
 
33
37
  super.onCreate(savedInstanceState);
34
38
 
35
- setContentView(R.layout.activity_main);
36
-
37
-
38
-
39
- mPager = (ViewPager) findViewById(R.id.pager);
40
-
41
- pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
42
-
43
- mPager.setAdapter(pagerAdapter);
44
-
45
-
46
-
47
- // タブの設定
48
-
49
- TabLayout tabLayout = findViewById(R.id.tab_layout);
50
-
51
- tabLayout.setupWithViewPager(mPager);
52
-
53
-
54
-
55
-
56
-
57
- }
39
+
40
+
41
+ binding = ActivityMainBinding.inflate(getLayoutInflater());
42
+
43
+ setContentView(binding.getRoot());
44
+
45
+
46
+
47
+ sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
48
+
49
+ ViewPager viewPager = binding.viewPager;
50
+
51
+ viewPager.setAdapter(sectionsPagerAdapter);
52
+
53
+ TabLayout tabs = binding.tabs;
54
+
55
+ tabs.setupWithViewPager(viewPager);
56
+
57
+ FloatingActionButton fab = binding.fab;
58
+
59
+
60
+
61
+ fab.setOnClickListener(new View.OnClickListener() {
62
+
63
+ @Override
64
+
65
+ public void onClick(View view) {
66
+
67
+ Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
68
+
69
+ .setAction("Action", null).show();
70
+
71
+ }
72
+
73
+ });
74
+
75
+
76
+
77
+ feedMultiple();
78
+
79
+ }
80
+
81
+
82
+
83
+ private Thread thread;
84
+
85
+
86
+
87
+ private void feedMultiple() {
88
+
89
+
90
+
91
+ if (thread != null)
92
+
93
+ thread.interrupt();
94
+
95
+
96
+
97
+ final Runnable runnable = new Runnable() {
98
+
99
+
100
+
101
+ @Override
102
+
103
+ public void run() {
104
+
105
+ if( sectionsPagerAdapter.getCurrentFragment() instanceof GraphFragment) {
106
+
107
+ ((GraphFragment) sectionsPagerAdapter.getCurrentFragment()).setChart();
108
+
109
+ }
110
+
111
+ }
112
+
113
+ };
114
+
115
+
116
+
117
+ thread = new Thread(new Runnable() {
118
+
119
+
120
+
121
+ @Override
122
+
123
+ public void run() {
124
+
125
+ for (int i = 0; i < 1000; i++) {
126
+
127
+
128
+
129
+ // Don't generate garbage runnables inside the loop.
130
+
131
+ runOnUiThread(runnable);
132
+
133
+
134
+
135
+ try {
136
+
137
+ Thread.sleep(1000);
138
+
139
+ } catch (InterruptedException e) {
140
+
141
+ e.printStackTrace();
142
+
143
+ }
144
+
145
+ }
146
+
147
+ }
148
+
149
+ });
150
+
151
+
152
+
153
+ thread.start();
154
+
155
+ }
156
+
157
+ }
58
158
 
59
159
  ```
60
160
 
@@ -64,15 +164,45 @@
64
164
 
65
165
  ```java
66
166
 
167
+
168
+
169
+ /**
170
+
171
+ * A placeholder fragment containing a simple view.
172
+
173
+ */
174
+
67
175
  public class GraphFragment extends Fragment {
68
176
 
69
177
 
70
178
 
71
- private View rootView;
179
+ private PageViewModel pageViewModel;
180
+
72
-
181
+ private GraphFragmentBinding binding;
182
+
183
+
184
+
73
- private LineChart mChart;
185
+ private LineChart chart;
186
+
74
-
187
+ private MainActivity activity;
188
+
189
+
190
+
75
-
191
+ public static GraphFragment newInstance() {
192
+
193
+ GraphFragment fragment = new GraphFragment();
194
+
195
+ Bundle bundle = new Bundle();
196
+
197
+ // bundle.putInt(ARG_SECTION_NUMBER, index);
198
+
199
+ fragment.setArguments(bundle);
200
+
201
+ return fragment;
202
+
203
+ }
204
+
205
+
76
206
 
77
207
  @Override
78
208
 
@@ -80,25 +210,69 @@
80
210
 
81
211
  super.onCreate(savedInstanceState);
82
212
 
213
+ activity = (MainActivity) getActivity();
214
+
215
+ pageViewModel = new ViewModelProvider(activity).get(PageViewModel.class);
216
+
217
+
218
+
219
+ // Create the observer which updates the UI.
220
+
221
+ final Observer<LineChart> observer = new Observer<LineChart>() {
222
+
223
+ @Override
224
+
225
+ public void onChanged(@Nullable final LineChart newName) {
226
+
227
+ // Update the UI, in this case, a TextView.
228
+
229
+ addEntry();
230
+
231
+ }
232
+
233
+ };
234
+
235
+
236
+
237
+ // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
238
+
239
+ pageViewModel.getLineChart().observe(this, observer);
240
+
83
241
  }
84
242
 
85
243
 
86
244
 
87
245
  @Override
88
246
 
89
- public View onCreateView(@NonNull LayoutInflater inflater,
247
+ public View onCreateView(
90
-
248
+
91
- ViewGroup container,
249
+ @NonNull LayoutInflater inflater, ViewGroup container,
92
-
250
+
93
- Bundle savedInstanceState) {
251
+ Bundle savedInstanceState) {
94
-
252
+
253
+
254
+
95
- rootView = inflater.inflate(R.layout.fragment_graph, container, false);
255
+ binding = GraphFragmentBinding.inflate(inflater,container,false);;
256
+
96
-
257
+ View root = binding.getRoot();
258
+
259
+ if(pageViewModel.getValue() == null){
260
+
261
+ chart = binding.chart1;
262
+
263
+ initChart();
264
+
265
+ }
266
+
267
+ else{
268
+
97
- mChart = rootView.findViewById(R.id.line_chart);
269
+ chart = pageViewModel.getValue();
270
+
98
-
271
+ }
99
-
100
-
272
+
273
+
274
+
101
- return rootView;
275
+ return root;
102
276
 
103
277
  }
104
278
 
@@ -106,31 +280,203 @@
106
280
 
107
281
  @Override
108
282
 
109
- public void onActivityCreated (Bundle savedInstanceState) {
110
-
111
- super.onActivityCreated(savedInstanceState);
112
-
113
- }
114
-
115
-
116
-
117
- public void setData() {
118
-
119
- //mchartにデータセット 略
120
-
121
- }
122
-
123
-
124
-
125
- @Override
126
-
127
- public void onSaveInstanceState(@NonNull Bundle outState) {
128
-
129
- super.onSaveInstanceState(outState);
130
-
131
- // mchartを一時退避する?
132
-
133
- }
283
+ public void onDestroyView() {
284
+
285
+ super.onDestroyView();
286
+
287
+ binding = null;
288
+
289
+ }
290
+
291
+
292
+
293
+ public void setChart(){
294
+
295
+ pageViewModel.setChart(chart);
296
+
297
+ }
298
+
299
+
300
+
301
+ public void initChart(){
302
+
303
+
304
+
305
+ // enable description text
306
+
307
+ chart.getDescription().setEnabled(true);
308
+
309
+
310
+
311
+ // enable touch gestures
312
+
313
+ chart.setTouchEnabled(true);
314
+
315
+
316
+
317
+ // enable scaling and dragging
318
+
319
+ chart.setDragEnabled(true);
320
+
321
+ chart.setScaleEnabled(true);
322
+
323
+ chart.setDrawGridBackground(false);
324
+
325
+
326
+
327
+ // if disabled, scaling can be done on x- and y-axis separately
328
+
329
+ chart.setPinchZoom(true);
330
+
331
+
332
+
333
+ // set an alternative background color
334
+
335
+ chart.setBackgroundColor(Color.LTGRAY);
336
+
337
+
338
+
339
+ LineData data = new LineData();
340
+
341
+ data.setValueTextColor(Color.WHITE);
342
+
343
+
344
+
345
+ // add empty data
346
+
347
+ chart.setData(data);
348
+
349
+
350
+
351
+ XAxis xl = chart.getXAxis();
352
+
353
+ xl.setLabelRotationAngle(45);
354
+
355
+ xl.setTextColor(Color.WHITE);
356
+
357
+ xl.setDrawGridLines(false);
358
+
359
+ xl.setAvoidFirstLastClipping(true);
360
+
361
+ xl.setEnabled(true);
362
+
363
+
364
+
365
+ YAxis leftAxis = chart.getAxisLeft();
366
+
367
+ leftAxis.setTextColor(Color.WHITE);
368
+
369
+ leftAxis.setAxisMaximum(100f);
370
+
371
+ leftAxis.setAxisMinimum(0f);
372
+
373
+ leftAxis.setDrawGridLines(true);
374
+
375
+
376
+
377
+ YAxis rightAxis = chart.getAxisRight();
378
+
379
+ rightAxis.setEnabled(false);
380
+
381
+ }
382
+
383
+
384
+
385
+ public void addEntry() {
386
+
387
+ LineData data = chart.getData();
388
+
389
+
390
+
391
+ if (data != null) {
392
+
393
+
394
+
395
+ ILineDataSet set = data.getDataSetByIndex(0);
396
+
397
+ // set.addEntry(...); // can be called as well
398
+
399
+
400
+
401
+ if (set == null) {
402
+
403
+ set = createSet();
404
+
405
+ data.addDataSet(set);
406
+
407
+ }
408
+
409
+
410
+
411
+ data.addEntry(new Entry(set.getEntryCount(), (float) (Math.random() * 40) + 30f), 0);
412
+
413
+ data.notifyDataChanged();
414
+
415
+
416
+
417
+ // let the chart know it's data has changed
418
+
419
+ chart.notifyDataSetChanged();
420
+
421
+
422
+
423
+ // limit the number of visible entries
424
+
425
+ chart.setVisibleXRangeMaximum(120);
426
+
427
+ // chart.setVisibleYRange(30, AxisDependency.LEFT);
428
+
429
+
430
+
431
+ // move to the latest entry
432
+
433
+ chart.moveViewToX(data.getEntryCount());
434
+
435
+
436
+
437
+ // this automatically refreshes the chart (calls invalidate())
438
+
439
+ // chart.moveViewTo(data.getXValCount()-7, 55f,
440
+
441
+ // AxisDependency.LEFT);
442
+
443
+ }
444
+
445
+ }
446
+
447
+
448
+
449
+ private LineDataSet createSet() {
450
+
451
+
452
+
453
+ LineDataSet set = new LineDataSet(null, "Dynamic Data");
454
+
455
+ set.setAxisDependency(AxisDependency.LEFT);
456
+
457
+ set.setColor(ColorTemplate.getHoloBlue());
458
+
459
+ set.setCircleColor(Color.WHITE);
460
+
461
+ set.setLineWidth(2f);
462
+
463
+ set.setCircleRadius(4f);
464
+
465
+ set.setFillAlpha(65);
466
+
467
+ set.setFillColor(ColorTemplate.getHoloBlue());
468
+
469
+ set.setHighLightColor(Color.rgb(244, 117, 117));
470
+
471
+ set.setValueTextColor(Color.WHITE);
472
+
473
+ set.setValueTextSize(9f);
474
+
475
+ set.setDrawValues(false);
476
+
477
+ return set;
478
+
479
+ }
134
480
 
135
481
  }
136
482
 
@@ -140,6 +486,108 @@
140
486
 
141
487
 
142
488
 
489
+ pageViewModel.java
490
+
491
+ ```java
492
+
493
+ package com.example.myapplication.ui.main;
494
+
495
+
496
+
497
+ import androidx.arch.core.util.Function;
498
+
499
+ import androidx.lifecycle.LiveData;
500
+
501
+ import androidx.lifecycle.MutableLiveData;
502
+
503
+ import androidx.lifecycle.Transformations;
504
+
505
+ import androidx.lifecycle.ViewModel;
506
+
507
+
508
+
509
+ import com.github.mikephil.charting.charts.LineChart;
510
+
511
+ import com.github.mikephil.charting.data.LineData;
512
+
513
+
514
+
515
+ public class PageViewModel extends ViewModel {
516
+
517
+
518
+
519
+ private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
520
+
521
+
522
+
523
+ private MutableLiveData<LineChart> myLineChart = new MutableLiveData<>();
524
+
525
+
526
+
527
+ private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
528
+
529
+ @Override
530
+
531
+ public String apply(Integer input) {
532
+
533
+ return "Hello world from section: " + input;
534
+
535
+ }
536
+
537
+ });
538
+
539
+
540
+
541
+ public void setIndex(int index) {
542
+
543
+ mIndex.setValue(index);
544
+
545
+ }
546
+
547
+
548
+
549
+ public LiveData<String> getText() {
550
+
551
+ return mText;
552
+
553
+ }
554
+
555
+
556
+
557
+ public void setChart(LineChart m){
558
+
559
+ myLineChart.setValue(m);
560
+
561
+ }
562
+
563
+
564
+
565
+ public LiveData<LineChart> getLineChart() {
566
+
567
+ if (myLineChart == null) {
568
+
569
+ myLineChart = new MutableLiveData<LineChart>();
570
+
571
+ }
572
+
573
+ return myLineChart;
574
+
575
+ }
576
+
577
+
578
+
579
+ public LineChart getValue(){
580
+
581
+ return myLineChart.getValue();
582
+
583
+ }
584
+
585
+ }
586
+
587
+ ```
588
+
589
+
590
+
143
591
  fragment_graph.xml
144
592
 
145
593
  ```xml