public class Tab1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
HorizontalBarChart barChart = (HorizontalBarChart) rootView.findViewById(R.id.barchartnew);
ArrayList<BarEntry> bargroup1 = new ArrayList<>();
bargroup1.add(new BarEntry(8f, 0));
return rootView;
}
public void test() {
// Here I want to access bargroup1
}
}
如何访问bargroup1
中的数组列表变量public void test()
?
我尝试在ArrayList bargroup1;
下方插入public class Tab1 extends Fragment {
并删除ArrayList<BarEntry> bargroup1 = new ArrayList<>();
,但随后我的应用崩溃了。
答案 0 :(得分:4)
将var声明为实例变量,在onCreateView
方法中初始化它,然后您可以在其他方法中使用var:
public class Tab1 extends Fragment {
ArrayList<BarEntry> bargroup1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
HorizontalBarChart barChart = (HorizontalBarChart)rootView.findViewById(R.id.barchartnew);
bargroup1 = new ArrayList<>();
bargroup1.add(new BarEntry(8f, 0));
return rootView;
}
public void test(){
// Here I want to access bargroup1
}
}