繼官方Android「Hello World」教程之後,會生成兩個佈局文件:activity_main.xml
和fragment_main.xml
。同時,類MainActivity
中生成嵌套類PlaceholderFragment
。然後教程要求更改fragment_main.xml
而不是activity_main.xml
。關於Android教程「hello world」的疑問
我的第一個問題: 爲什麼要改變fragment_main.xml
而不是activity_main.xml
?
第二個問題: 如何使用類PlaceholderFragment
?誰叫它?由於UI設計在fragment_main.xml
中,因此MainActivity
可以如何顯示UI?
activity_main.xml
:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myfirstapp.MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myfirstapp.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
感謝。 Deryk
閱讀:http://developer.android.com/guide/components/fragments.html – Dyrborg
雖然有一個「fragment_main.xml」和一個佔位符自動創建,我沒有使用片段。那個鏈接沒有提到我的問題。 – derek
使用最新的SDK更新,片段活動是默認的空白項目默認爲現在的內容。這不是一個受歡迎的變化,請參閱http://code.google.com/p/android/issues/detail?id=67513 – NickT