目前我正在尝试抽象应用程序的基本UI,以便可以通过子片段进行扩展,继承主要元素,例如导航和设置菜单的元素。然后,孩子们将获取基本UI并创建UI的其余部分,但是当前除非您在子类中明确设置视图。 onCreate方法,结果是一个空白活动。
是否根本无法将内容视图设置在子类的oncreate之外的任何位置?
以下代码:
抽象基类:
public abstract class BaseUIActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
protected DrawerLayout drawer;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//generateUI(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu m){
getMenuInflater().inflate(R.menu.main, m);
return super.onCreateOptionsMenu(m);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {...}
@Override
public void onBackPressed() {...}
@Override
public boolean onNavigationItemSelected(MenuItem item) {...}
public void generateUI(int layoutID){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
Log.d("layoutID: ",""+String.valueOf(layoutID));
this.setContentView(layoutID);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
Log.d("Drawer: ", "" + String.valueOf(findViewById(R.id.drawer_layout)));
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
Log.d("Toggle: ", "" + String.valueOf(toggle));
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
}
示例儿童:
public class MainActivity extends BaseUIActivity implements OnNavigationItemSelectedListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//generateUI(R.layout.activity_main);
//listViewEvents = (ListView) findViewById(R.id.listViewEvents);
}
}
答案 0 :(得分:0)
您需要将setContentView(R.layout.activity_main)
移动到MainActivity
而不是抽象类(BaseUIActivity
),因为这不会被实例化(这使得它变得抽象)。如果您想将一些代码放在基类中以便可以将Activity类中的实际代码保持较小,那么您可以这样做,但setContentView
应该在onCreate
中。将实例化的活动类 - 在您的情况下为MainActivity
。关注the tutorial here,它提供了一个很好的例子,说明了您要做的事情。