我目前有这个xml:
<TextView android:id="@+id/dummy"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/test"
android:textStyle="bold" />
我试图将其转换为 java 版本,以便我可以设置字体:
setContentView(R.layout.activity_main);
// the get the activity_main layout (getContentView method does not exist?)
FrameLayout layout = (FrameLayout) findViewById(android.R.id.content);
final TextView textView = new TextView(context);
textView.setId(R.id.dummy);
FrameLayout.LayoutParams contentLayout = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
contentLayout.gravity = Gravity.CENTER;
textView.setText(R.string.test);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/arial.ttf");
textView.setTypeface(tf);
layout.addView(textView, contentLayout);
我遇到的问题是重力不起作用或 match_parent。文本最终位于右上角,而不是像在 xml 版本上那样位于中心。