質問するログイン新規登録

質問編集履歴

1

viewModelを使った方法に変更

2021/12/13 13:36

投稿

luckyclock
luckyclock

スコア74

title CHANGED
File without changes
body CHANGED
@@ -5,70 +5,294 @@
5
5
  と戻ってくるとタブ3に移動するとタブ1のフラグメントのインスタンスが消える関係で
6
6
  タブ1フラグメントでもってるmChartのインスタンスも消えてしまい、
7
7
  描画データがなくなってしまいます。
8
- なんとか描画データ継続し表示したいのですどうすればよいしょうか?
8
+ viewModel使っ書いてみましたが、タブ1→3→1再描画されません。
9
- なんとなくonSaveInstanceState使ってmchartを保持してoncreateで復元すればできるような気もす
10
- るのですが・・・
11
- あるいはタブ移動したときにフラグメントのインスタンスが破棄されないようにするとか?
12
9
 
13
10
  MainActivity.java
14
11
  ```java
12
+
13
+ public class MainActivity extends AppCompatActivity {
14
+
15
+ private ActivityMainBinding binding;
16
+ private SectionsPagerAdapter sectionsPagerAdapter;
15
17
  @Override
16
18
  protected void onCreate(Bundle savedInstanceState) {
17
19
  super.onCreate(savedInstanceState);
18
- setContentView(R.layout.activity_main);
19
20
 
20
- mPager = (ViewPager) findViewById(R.id.pager);
21
- pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
21
+ binding = ActivityMainBinding.inflate(getLayoutInflater());
22
- mPager.setAdapter(pagerAdapter);
22
+ setContentView(binding.getRoot());
23
23
 
24
+ sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
24
- // タブの設定
25
+ ViewPager viewPager = binding.viewPager;
26
+ viewPager.setAdapter(sectionsPagerAdapter);
25
- TabLayout tabLayout = findViewById(R.id.tab_layout);
27
+ TabLayout tabs = binding.tabs;
26
- tabLayout.setupWithViewPager(mPager);
28
+ tabs.setupWithViewPager(viewPager);
29
+ FloatingActionButton fab = binding.fab;
27
30
 
31
+ fab.setOnClickListener(new View.OnClickListener() {
32
+ @Override
33
+ public void onClick(View view) {
34
+ Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
35
+ .setAction("Action", null).show();
36
+ }
37
+ });
28
38
 
39
+ feedMultiple();
29
40
  }
41
+
42
+ private Thread thread;
43
+
44
+ private void feedMultiple() {
45
+
46
+ if (thread != null)
47
+ thread.interrupt();
48
+
49
+ final Runnable runnable = new Runnable() {
50
+
51
+ @Override
52
+ public void run() {
53
+ if( sectionsPagerAdapter.getCurrentFragment() instanceof GraphFragment) {
54
+ ((GraphFragment) sectionsPagerAdapter.getCurrentFragment()).setChart();
55
+ }
56
+ }
57
+ };
58
+
59
+ thread = new Thread(new Runnable() {
60
+
61
+ @Override
62
+ public void run() {
63
+ for (int i = 0; i < 1000; i++) {
64
+
65
+ // Don't generate garbage runnables inside the loop.
66
+ runOnUiThread(runnable);
67
+
68
+ try {
69
+ Thread.sleep(1000);
70
+ } catch (InterruptedException e) {
71
+ e.printStackTrace();
72
+ }
73
+ }
74
+ }
75
+ });
76
+
77
+ thread.start();
78
+ }
79
+ }
30
80
  ```
31
81
 
32
82
  GraphFragment.java
33
83
  ```java
84
+
85
+ /**
86
+ * A placeholder fragment containing a simple view.
87
+ */
34
88
  public class GraphFragment extends Fragment {
35
89
 
36
- private View rootView;
90
+ private PageViewModel pageViewModel;
91
+ private GraphFragmentBinding binding;
92
+
37
- private LineChart mChart;
93
+ private LineChart chart;
38
-
94
+ private MainActivity activity;
95
+
96
+ public static GraphFragment newInstance() {
97
+ GraphFragment fragment = new GraphFragment();
98
+ Bundle bundle = new Bundle();
99
+ // bundle.putInt(ARG_SECTION_NUMBER, index);
100
+ fragment.setArguments(bundle);
101
+ return fragment;
102
+ }
103
+
39
104
  @Override
40
105
  public void onCreate(Bundle savedInstanceState) {
41
106
  super.onCreate(savedInstanceState);
107
+ activity = (MainActivity) getActivity();
108
+ pageViewModel = new ViewModelProvider(activity).get(PageViewModel.class);
109
+
110
+ // Create the observer which updates the UI.
111
+ final Observer<LineChart> observer = new Observer<LineChart>() {
112
+ @Override
113
+ public void onChanged(@Nullable final LineChart newName) {
114
+ // Update the UI, in this case, a TextView.
115
+ addEntry();
116
+ }
117
+ };
118
+
119
+ // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
120
+ pageViewModel.getLineChart().observe(this, observer);
42
121
  }
43
122
 
44
123
  @Override
45
- public View onCreateView(@NonNull LayoutInflater inflater,
124
+ public View onCreateView(
46
- ViewGroup container,
125
+ @NonNull LayoutInflater inflater, ViewGroup container,
47
- Bundle savedInstanceState) {
126
+ Bundle savedInstanceState) {
127
+
48
- rootView = inflater.inflate(R.layout.fragment_graph, container, false);
128
+ binding = GraphFragmentBinding.inflate(inflater,container,false);;
129
+ View root = binding.getRoot();
130
+ if(pageViewModel.getValue() == null){
131
+ chart = binding.chart1;
132
+ initChart();
133
+ }
134
+ else{
49
- mChart = rootView.findViewById(R.id.line_chart);
135
+ chart = pageViewModel.getValue();
50
-
136
+ }
137
+
51
- return rootView;
138
+ return root;
52
139
  }
53
140
 
54
141
  @Override
55
- public void onActivityCreated (Bundle savedInstanceState) {
142
+ public void onDestroyView() {
56
- super.onActivityCreated(savedInstanceState);
143
+ super.onDestroyView();
144
+ binding = null;
57
145
  }
58
146
 
59
- public void setData() {
147
+ public void setChart(){
60
- //mchartにデータセット 略
148
+ pageViewModel.setChart(chart);
61
149
  }
62
150
 
63
- @Override
151
+ public void initChart(){
152
+
153
+ // enable description text
64
- public void onSaveInstanceState(@NonNull Bundle outState) {
154
+ chart.getDescription().setEnabled(true);
155
+
156
+ // enable touch gestures
157
+ chart.setTouchEnabled(true);
158
+
159
+ // enable scaling and dragging
160
+ chart.setDragEnabled(true);
65
- super.onSaveInstanceState(outState);
161
+ chart.setScaleEnabled(true);
162
+ chart.setDrawGridBackground(false);
163
+
164
+ // if disabled, scaling can be done on x- and y-axis separately
165
+ chart.setPinchZoom(true);
166
+
167
+ // set an alternative background color
168
+ chart.setBackgroundColor(Color.LTGRAY);
169
+
170
+ LineData data = new LineData();
171
+ data.setValueTextColor(Color.WHITE);
172
+
66
- // mchartを一時退避する?
173
+ // add empty data
174
+ chart.setData(data);
175
+
176
+ XAxis xl = chart.getXAxis();
177
+ xl.setLabelRotationAngle(45);
178
+ xl.setTextColor(Color.WHITE);
179
+ xl.setDrawGridLines(false);
180
+ xl.setAvoidFirstLastClipping(true);
181
+ xl.setEnabled(true);
182
+
183
+ YAxis leftAxis = chart.getAxisLeft();
184
+ leftAxis.setTextColor(Color.WHITE);
185
+ leftAxis.setAxisMaximum(100f);
186
+ leftAxis.setAxisMinimum(0f);
187
+ leftAxis.setDrawGridLines(true);
188
+
189
+ YAxis rightAxis = chart.getAxisRight();
190
+ rightAxis.setEnabled(false);
67
- }
191
+ }
192
+
193
+ public void addEntry() {
194
+ LineData data = chart.getData();
195
+
196
+ if (data != null) {
197
+
198
+ ILineDataSet set = data.getDataSetByIndex(0);
199
+ // set.addEntry(...); // can be called as well
200
+
201
+ if (set == null) {
202
+ set = createSet();
203
+ data.addDataSet(set);
204
+ }
205
+
206
+ data.addEntry(new Entry(set.getEntryCount(), (float) (Math.random() * 40) + 30f), 0);
207
+ data.notifyDataChanged();
208
+
209
+ // let the chart know it's data has changed
210
+ chart.notifyDataSetChanged();
211
+
212
+ // limit the number of visible entries
213
+ chart.setVisibleXRangeMaximum(120);
214
+ // chart.setVisibleYRange(30, AxisDependency.LEFT);
215
+
216
+ // move to the latest entry
217
+ chart.moveViewToX(data.getEntryCount());
218
+
219
+ // this automatically refreshes the chart (calls invalidate())
220
+ // chart.moveViewTo(data.getXValCount()-7, 55f,
221
+ // AxisDependency.LEFT);
222
+ }
223
+ }
224
+
225
+ private LineDataSet createSet() {
226
+
227
+ LineDataSet set = new LineDataSet(null, "Dynamic Data");
228
+ set.setAxisDependency(AxisDependency.LEFT);
229
+ set.setColor(ColorTemplate.getHoloBlue());
230
+ set.setCircleColor(Color.WHITE);
231
+ set.setLineWidth(2f);
232
+ set.setCircleRadius(4f);
233
+ set.setFillAlpha(65);
234
+ set.setFillColor(ColorTemplate.getHoloBlue());
235
+ set.setHighLightColor(Color.rgb(244, 117, 117));
236
+ set.setValueTextColor(Color.WHITE);
237
+ set.setValueTextSize(9f);
238
+ set.setDrawValues(false);
239
+ return set;
240
+ }
68
241
  }
69
242
 
70
243
  ```
71
244
 
245
+ pageViewModel.java
246
+ ```java
247
+ package com.example.myapplication.ui.main;
248
+
249
+ import androidx.arch.core.util.Function;
250
+ import androidx.lifecycle.LiveData;
251
+ import androidx.lifecycle.MutableLiveData;
252
+ import androidx.lifecycle.Transformations;
253
+ import androidx.lifecycle.ViewModel;
254
+
255
+ import com.github.mikephil.charting.charts.LineChart;
256
+ import com.github.mikephil.charting.data.LineData;
257
+
258
+ public class PageViewModel extends ViewModel {
259
+
260
+ private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
261
+
262
+ private MutableLiveData<LineChart> myLineChart = new MutableLiveData<>();
263
+
264
+ private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
265
+ @Override
266
+ public String apply(Integer input) {
267
+ return "Hello world from section: " + input;
268
+ }
269
+ });
270
+
271
+ public void setIndex(int index) {
272
+ mIndex.setValue(index);
273
+ }
274
+
275
+ public LiveData<String> getText() {
276
+ return mText;
277
+ }
278
+
279
+ public void setChart(LineChart m){
280
+ myLineChart.setValue(m);
281
+ }
282
+
283
+ public LiveData<LineChart> getLineChart() {
284
+ if (myLineChart == null) {
285
+ myLineChart = new MutableLiveData<LineChart>();
286
+ }
287
+ return myLineChart;
288
+ }
289
+
290
+ public LineChart getValue(){
291
+ return myLineChart.getValue();
292
+ }
293
+ }
294
+ ```
295
+
72
296
  fragment_graph.xml
73
297
  ```xml
74
298
  <?xml version="1.0" encoding="utf-8"?>