0
我对android开发非常陌生,我正在尝试学习如何以编程方式将工具栏添加到相对视图。从本质上讲,我试图在代码中执行空白项目模板,而不是使用基于XML的方法。我的应用程序将启动,但我看到的是我添加的TextView,并没有看到工具栏或菜单膨胀,并放置在屏幕顶部的工具栏上。这里是我到目前为止的代码:以编程方式将工具栏添加到Android中的RelativeView
public class MainActivity extends AppCompatActivity {
private RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the relative layout programmatically
createRelativeLayout();
// Set the content view with the instantiated relative layout
setContentView(this.relativeLayout);
// Create and add the action bar
setSupportActionBar(createToolbar());
// Create a text view and add it
this.relativeLayout.addView(createTextView());
}
private void createRelativeLayout() {
relativeLayout = new RelativeLayout(this);
// Specifies the layout properties
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
relativeLayout.setLayoutParams(relativeParams);
}
private TextView createTextView() {
TextView textView = new TextView(this);
// Set initial layout parameters
RelativeLayout.LayoutParams textViewParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
// Set alignment parameters
textViewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
textViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
textViewParams.setMargins(0, 82, 0, 0);
textView.setText(R.string.app_name);
textView.setLayoutParams(textViewParams);
return textView;
}
private Toolbar createToolbar() {
Toolbar toolbar = new Toolbar(this);
Toolbar.LayoutParams toolBarParams = new Toolbar.LayoutParams(
Toolbar.LayoutParams.MATCH_PARENT,
R.attr.actionBarSize
);
toolbar.setLayoutParams(toolBarParams);
toolbar.setBackgroundColor(Color.BLUE);
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay);
toolbar.setVisibility(View.VISIBLE);
return toolbar;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
任何帮助,非常感谢,谢谢。