Android 用于单个视图的绘图应用需要在多视图底部导航中工作 Activity 应用

Android drawing app intended for a single View needs to work in multi-view Bottom Navigation Activity app

我是一个全新的 Android 开发者,此刻我很迷茫。我正在关注此 tutorial,因为我尝试在我的应用程序中启用对视图的绘图,这是一个具有三个选项卡或片段的 "Bottom Navigation Activity" 项目。请参阅下面的屏幕截图:

问题是本教程适用于具有单个视图和单个标准 MainActivity 的应用程序。本例在项目的MainActivity.javaclass中的onCreate()方法中使用了如下代码:

public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState):
PaintView paintView = new PaintView(content: this):
setContentView(paintView);
  }

}

当我构建单视图应用程序时,代码运行良好。没有问题。但是在我的 "Bottom Navigation Activity" 项目中无法正常工作,因为片段使用的 ViewModel 类型不提供 View class 急需的方法。我的应用有 3 个片段,第一个片段名为 HomeFragment。我希望我所有的绘画都发生在这个片段上。此片段的默认 onCreateView() 方法如下所示:

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;
 }
}

请参阅下面的屏幕截图以了解我尝试执行的操作。您会看到我在名为 PaintView 的项目中添加了一个 View class(就像在教程中创建的一样),其中包含所有绘图代码。

不幸的是,它产生了以下编译错误:

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

任何有关如何实现教程的 PaintView class 以便我可以使用它的方法在 "HomeFragment" 上绘图的提示,我们将不胜感激。

非常感谢,

沃尔夫

您正在做的是尝试用 PaintView class 创建一个 HomeViewModel 对象,这是不可能的。如果你想将 PaintView 设置为你的 HomeFragment 的视图,你需要 return 它的一个对象作为 :

    //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;

    }

希望对您有所帮助。


Learn more about Fragment here

Learn more about ViewModel here