タブレイアウト+viewPagerにて
3タブフラグメントを構築しています。
タブ1ではMPChartを使用してグラフ描画しているのですが、
タブ1→タブ2→タブ3→タブ2→タブ1
と戻ってくるとタブ3に移動するとタブ1のフラグメントのインスタンスが消える関係で
タブ1フラグメントでもってるmChartのインスタンスも消えてしまい、
描画データがなくなってしまいます。
viewModelを使って書いてみましたが、タブ1→3→1で再描画されません。
MainActivity.java
java
1 2public class MainActivity extends AppCompatActivity { 3 4 private ActivityMainBinding binding; 5 private SectionsPagerAdapter sectionsPagerAdapter; 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 10 binding = ActivityMainBinding.inflate(getLayoutInflater()); 11 setContentView(binding.getRoot()); 12 13 sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager()); 14 ViewPager viewPager = binding.viewPager; 15 viewPager.setAdapter(sectionsPagerAdapter); 16 TabLayout tabs = binding.tabs; 17 tabs.setupWithViewPager(viewPager); 18 FloatingActionButton fab = binding.fab; 19 20 fab.setOnClickListener(new View.OnClickListener() { 21 @Override 22 public void onClick(View view) { 23 Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 24 .setAction("Action", null).show(); 25 } 26 }); 27 28 feedMultiple(); 29 } 30 31 private Thread thread; 32 33 private void feedMultiple() { 34 35 if (thread != null) 36 thread.interrupt(); 37 38 final Runnable runnable = new Runnable() { 39 40 @Override 41 public void run() { 42 if( sectionsPagerAdapter.getCurrentFragment() instanceof GraphFragment) { 43 ((GraphFragment) sectionsPagerAdapter.getCurrentFragment()).setChart(); 44 } 45 } 46 }; 47 48 thread = new Thread(new Runnable() { 49 50 @Override 51 public void run() { 52 for (int i = 0; i < 1000; i++) { 53 54 // Don't generate garbage runnables inside the loop. 55 runOnUiThread(runnable); 56 57 try { 58 Thread.sleep(1000); 59 } catch (InterruptedException e) { 60 e.printStackTrace(); 61 } 62 } 63 } 64 }); 65 66 thread.start(); 67 } 68}
GraphFragment.java
java
1 2/** 3 * A placeholder fragment containing a simple view. 4 */ 5public class GraphFragment extends Fragment { 6 7 private PageViewModel pageViewModel; 8 private GraphFragmentBinding binding; 9 10 private LineChart chart; 11 private MainActivity activity; 12 13 public static GraphFragment newInstance() { 14 GraphFragment fragment = new GraphFragment(); 15 Bundle bundle = new Bundle(); 16// bundle.putInt(ARG_SECTION_NUMBER, index); 17 fragment.setArguments(bundle); 18 return fragment; 19 } 20 21 @Override 22 public void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 activity = (MainActivity) getActivity(); 25 pageViewModel = new ViewModelProvider(activity).get(PageViewModel.class); 26 27 // Create the observer which updates the UI. 28 final Observer<LineChart> observer = new Observer<LineChart>() { 29 @Override 30 public void onChanged(@Nullable final LineChart newName) { 31 // Update the UI, in this case, a TextView. 32 addEntry(); 33 } 34 }; 35 36 // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer. 37 pageViewModel.getLineChart().observe(this, observer); 38 } 39 40 @Override 41 public View onCreateView( 42 @NonNull LayoutInflater inflater, ViewGroup container, 43 Bundle savedInstanceState) { 44 45 binding = GraphFragmentBinding.inflate(inflater,container,false);; 46 View root = binding.getRoot(); 47 if(pageViewModel.getValue() == null){ 48 chart = binding.chart1; 49 initChart(); 50 } 51 else{ 52 chart = pageViewModel.getValue(); 53 } 54 55 return root; 56 } 57 58 @Override 59 public void onDestroyView() { 60 super.onDestroyView(); 61 binding = null; 62 } 63 64 public void setChart(){ 65 pageViewModel.setChart(chart); 66 } 67 68 public void initChart(){ 69 70 // enable description text 71 chart.getDescription().setEnabled(true); 72 73 // enable touch gestures 74 chart.setTouchEnabled(true); 75 76 // enable scaling and dragging 77 chart.setDragEnabled(true); 78 chart.setScaleEnabled(true); 79 chart.setDrawGridBackground(false); 80 81 // if disabled, scaling can be done on x- and y-axis separately 82 chart.setPinchZoom(true); 83 84 // set an alternative background color 85 chart.setBackgroundColor(Color.LTGRAY); 86 87 LineData data = new LineData(); 88 data.setValueTextColor(Color.WHITE); 89 90 // add empty data 91 chart.setData(data); 92 93 XAxis xl = chart.getXAxis(); 94 xl.setLabelRotationAngle(45); 95 xl.setTextColor(Color.WHITE); 96 xl.setDrawGridLines(false); 97 xl.setAvoidFirstLastClipping(true); 98 xl.setEnabled(true); 99 100 YAxis leftAxis = chart.getAxisLeft(); 101 leftAxis.setTextColor(Color.WHITE); 102 leftAxis.setAxisMaximum(100f); 103 leftAxis.setAxisMinimum(0f); 104 leftAxis.setDrawGridLines(true); 105 106 YAxis rightAxis = chart.getAxisRight(); 107 rightAxis.setEnabled(false); 108 } 109 110 public void addEntry() { 111 LineData data = chart.getData(); 112 113 if (data != null) { 114 115 ILineDataSet set = data.getDataSetByIndex(0); 116 // set.addEntry(...); // can be called as well 117 118 if (set == null) { 119 set = createSet(); 120 data.addDataSet(set); 121 } 122 123 data.addEntry(new Entry(set.getEntryCount(), (float) (Math.random() * 40) + 30f), 0); 124 data.notifyDataChanged(); 125 126 // let the chart know it's data has changed 127 chart.notifyDataSetChanged(); 128 129 // limit the number of visible entries 130 chart.setVisibleXRangeMaximum(120); 131 // chart.setVisibleYRange(30, AxisDependency.LEFT); 132 133 // move to the latest entry 134 chart.moveViewToX(data.getEntryCount()); 135 136 // this automatically refreshes the chart (calls invalidate()) 137 // chart.moveViewTo(data.getXValCount()-7, 55f, 138 // AxisDependency.LEFT); 139 } 140 } 141 142 private LineDataSet createSet() { 143 144 LineDataSet set = new LineDataSet(null, "Dynamic Data"); 145 set.setAxisDependency(AxisDependency.LEFT); 146 set.setColor(ColorTemplate.getHoloBlue()); 147 set.setCircleColor(Color.WHITE); 148 set.setLineWidth(2f); 149 set.setCircleRadius(4f); 150 set.setFillAlpha(65); 151 set.setFillColor(ColorTemplate.getHoloBlue()); 152 set.setHighLightColor(Color.rgb(244, 117, 117)); 153 set.setValueTextColor(Color.WHITE); 154 set.setValueTextSize(9f); 155 set.setDrawValues(false); 156 return set; 157 } 158} 159
pageViewModel.java
java
1package com.example.myapplication.ui.main; 2 3import androidx.arch.core.util.Function; 4import androidx.lifecycle.LiveData; 5import androidx.lifecycle.MutableLiveData; 6import androidx.lifecycle.Transformations; 7import androidx.lifecycle.ViewModel; 8 9import com.github.mikephil.charting.charts.LineChart; 10import com.github.mikephil.charting.data.LineData; 11 12public class PageViewModel extends ViewModel { 13 14 private MutableLiveData<Integer> mIndex = new MutableLiveData<>(); 15 16 private MutableLiveData<LineChart> myLineChart = new MutableLiveData<>(); 17 18 private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() { 19 @Override 20 public String apply(Integer input) { 21 return "Hello world from section: " + input; 22 } 23 }); 24 25 public void setIndex(int index) { 26 mIndex.setValue(index); 27 } 28 29 public LiveData<String> getText() { 30 return mText; 31 } 32 33 public void setChart(LineChart m){ 34 myLineChart.setValue(m); 35 } 36 37 public LiveData<LineChart> getLineChart() { 38 if (myLineChart == null) { 39 myLineChart = new MutableLiveData<LineChart>(); 40 } 41 return myLineChart; 42 } 43 44 public LineChart getValue(){ 45 return myLineChart.getValue(); 46 } 47}
fragment_graph.xml
xml
1<?xml version="1.0" encoding="utf-8"?> 2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" android:layout_width="match_parent" 4 android:layout_height="wrap_content"> 5 6 7 <com.github.mikephil.charting.charts.LineChart 8 android:id="@+id/line_chart" 9 android:layout_width="match_parent" 10 android:layout_height="match_parent" 11 /> 12 13 14</LinearLayout>
回答1件
あなたの回答
tips
プレビュー