本文介绍了可重用的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发的新手,但是我有相当多的Swing / WPF(C#)GUI经验。我想做的是以下事情:

I'm new to Android development, but I have quite some bit of Swing/WPF(C#) GUI experience. What I'm trying to do is the following:

我有一个带有3个独立视图的 BottomNavigationView 。每个视图都是作为片段实现的,该片段通过 OnNavigationItemSelectedListener 在MainActivity Java代码中显示/隐藏:

I have a BottomNavigationView with 3 separate views. Each view is implemented as a fragment that is shown/ hidden in the MainActivity java code through a OnNavigationItemSelectedListener:

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.one:
                findViewById(R.id.one).setVisibility(View.VISIBLE);
                findViewById(R.id.two).setVisibility(View.GONE);
                findViewById(R.id.threee).setVisibility(View.GONE);
                return true;
    // ... and so on

我的问题是接口的一部分其中两个片段是相同的,由一组 EditText ImageButton 组成。因此,我想到了创建可重用的东西,而不是将代码加倍。我的选择是在片段内部制作一个片段(但在互联网上我认为这是不建议的)或制作可重复使用的视图(,

在Java中


对于Java端如果要获取特定视图并添加到当前布局,则需要布局Inflater,然后将其添加到在活动中像这样查看在您的片段中考虑是否抛出任何错误

第一个选项:

View view = null;
LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.your_reusable_view, null);
your_main_root_view.addView(view);

第二个选项:

View child = getLayoutInflater().inflate(R.layout.your_reusable_view, null);
your_main_root_view.addView(child);

这篇关于可重用的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 02:52
查看更多