我在学习 Android 教程后遇到了同样的问题。 Jones 的上述回答解决了这个问题,但这里有一种在显示消息活动的布局 xml 文件中使用 android:paddingTop="?attr/actionBarSize" 的方法。
如果你按照教程Starting Another Activity 和Add Up Button for Low-level Activities,你最终会得到/java/com.something.myfirstapp/DisplayMessageActivity.java like:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displaymessage);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
上面的代码创建了一个超出此活动布局文件范围的新 TextView。相反,您要做的是重用已在 /res/layout/activity_display_message.xml 文件中声明的“Hello World”TextView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="my.vstore.myfirstapp.DisplayMessageActivity">
<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
给TextView添加一个idandroid:id="@+id/display_message",然后把paddingTop改成android:paddingTop="?attr/actionBarSize":
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="?attr/actionBarSize"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="my.vstore.myfirstapp.DisplayMessageActivity">
<TextView android:id="@+id/display_message"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
然后,找到TextView的id,在/java/com.something.myfirstapp/DisplayMessageActivity.java中设置Text:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displaymessage);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
// Find the text view
TextView textView = (TextView) findViewById(R.id.display_message);
textView.setTextSize(40);
textView.setText(message);
}
因此,您可以在显示消息活动的布局 xml 文件中使用 android:paddingTop="?attr/actionBarSize"。