Есть фрагмент, в котором метод onCreateVew:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
initializeData();
initializeAdapter();
return view;
}
Хочу вынести реализацию recyclerView отдельно в дополнительный метод и просто объявить его в onCreateView:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
initViews();
initializeData();
initializeAdapter();
return view;
}
private initViews() {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
но ругается на view.findViewById. Мол надо объявить. Подскажите как лучше сделать.
Вы обращаетесь к необъявленной переменной. Переменная, объявленная в к-л методе не видна за пределами этого метода. Выхода 2
Неправильный в данном случае - вынести переменную View view на уровень класса. Так она будет доступна во всех методах и внутренних классах класса. В данном случчае это не нужно и принесёт больше проблем, чем пользы.
Правильный способ - передать View view из метода onCreateView в метод initViews через аргументы последнего так:
private initViews(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
Вызывать теперь метод так:
initViews(view);
Продвижение своими сайтами как стратегия роста и независимости