I'm a completely new Android dev and am rather lost at the moment. I'm following this tutorial as I try to enable drawing to a view in my app which is a "Bottom Navigation Activity"
project that features three tabs--or fragments. See screenshot below:
The problem is that the tutorial is intended for an app with a single View and a single standard MainActivity. In this case, the following code is used in the onCreate()
method in the project's MainActivity.java
class:
public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState):
PaintView paintView = new PaintView(content: this):
setContentView(paintView);
}
}
When I build a single view app, the code works great. No issues. But things can't work in my "Bottom Navigation Activity"
project, because the fragments use a ViewModel
type that doesn't offer the much needed methods of the View
class. My app features 3 fragments, the first of which is named HomeFragment
. It is on this fragment that I want all my drawing to take place. The default onCreateView()
method for this fragment looks like so:
public class HomeFragment extends Fragment {
private HomeView Model homeViewModel;
public View onCreateView(@NonNull LayoutInflator inflater, ViewGroup container, Bundle savedInstanceState) {
homeViewModel = ViewModelProviders.of(fragment: this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, attachToRoot: false);
return root;
}
}
See screenshot below to see what I've tried to do. You will see that I've added a View
class to my project called PaintView
(just as created in the tutorial), which contains all the drawing code.
Unfortunately it generates the following compilation error:
Inferred type com.example.mobile_testapp_android_2_ui.home.PaintView for type parameter T is not within its bound; should extend androidx.lifecycle.ViewModel
Any tips on how I can implement the tutorial's PaintView class so that I can use its methods to draw on the "HomeFragment" would be deeply appreciated.
Thank you and very cordially,
Wulf
What you are doing is trying to create a HomeViewModel
object with the PaintView
class which is not possible. If you want to set PaintView
as the view of your HomeFragment
, you need to return an object of it as :
//you can return any kind of view object as you like
public View onCreateView(@NonNull LayoutInflator inflater, ViewGroup container, Bundle savedInstanceState) {
PaintView homeFragmentView = new PaintView(requireContext());
// PaintView class must extends View class
return homeFragmentView;
}
I hope, this helps.