初始化基本Activity类中的公共视图

时间:2017-11-20 06:46:22

标签: java android inheritance android-activity polymorphism

我有一个父活动NavigationActivity,它做了类似这样的事情:

public class NavigationActivity extends Activity {
    protected LinearLayout navigationBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        navigationBar = findViewById(R.id.navbar);
    }
}

它有一种方法可以设置navigationBar的可见性:

@Override
protected void setNavbarVisibility(int view) {
   if (this.navigationBar != null) {
       this.navigationBar.setVisibility(view);
   }
}

我的活动AdventureActivity扩展了NavigationActivity

public class AdventureActivity extends NavigationActivity {
    EditText title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstancState);

        renderAdventureLayout();
    }

    public void renderAdventureLayout() {
        Handler h = new Handler();

        title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(final View v, boolean hasFocus) {
                if (hasFocus) {
                    h.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            setNavbarVisibility(View.GONE);
                        }
                    }, 200);
                } else {
                    h.postDelayed(new Runnable() {
                        @Override 
                        public void run() {
                            setNavbarVisibility(View.VISIBLE);
                        }
                    }, 200);
                }
            }
        }
    }
}

现在,我没有必要在navigationBar中声明或初始化AdventureActivity,而且它最初已经可见。但是,setNavbarVisibility(View.GONE);语句似乎不适用于AdventureActivity,除非我在navigationBar中初始化NavigationActivity,因为根据调试器,{{1}如果它未在navigationBar中初始化,则为null。我发现在两个活动中初始化AdventureActivity都是多余的。

1 个答案:

答案 0 :(得分:2)

您尚未在任何一项活动中提供内容视图,从而导致findViewById()方法返回null

如果要创建这样的活动层次结构,这意味着NavigationActivity应该有一个抽象方法,子类应该实现:


    public abstract class NavigationActivity extends Activity {
        ...

        @LayoutRes
        protected abstract int getLayoutId();
    }

然后AdventureActivity将成为:


    public class AdventureActivity extends NavigationActivity {
        ...

        @Override
        @LayoutRes
        protected int getLayoutId() {
            return R.layout.some_activity;
        }
    }

现在在NavigationActivity#onCreate()


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());

        navigationBar = findViewById(R.id.navbar);
    }

这要求每个子类提供一个布局,其中存在LinearLayout,其ID为navbar,否则您的navigationBar最终会成为null