2015-04-04 25 views
0

Im以下this教程開始使用android。Android入門教程,爲什麼要使用片段?

在本教程中,他們要求你添加以下代碼:

/** 
* 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_display_message, 
        container, false); 
      return rootView; 
    } 

但這創建的類看起來是從來沒有使用過,如果我刪除代碼似乎正常工作的代碼。爲什麼我需要添加此代碼? S按2 sugested已經在那裏,他們說你需要它的onCreate:本教程給出如下:

The complete onCreate() method for DisplayMessageActivity now looks like this: 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 

// 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); 
} 

它不是下面的教程後,叫在那兒了,而在此之前被刪除,你不能編譯代碼。

回答

0

但這創建的類看起來是從來沒有使用過

是的,這就是,在活動的onCreate()方法:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_display_message); 

    if (savedInstanceState == null) { 
     getSupportFragmentManager().beginTransaction() 
      .add(R.id.container, new PlaceholderFragment()).commit(); 
    } 
} 

您將在add()電話通知PlaceholderFragmentif區塊內。

如果我刪除代碼的代碼似乎做工精細

然後你有不同的onCreate()方法,或者你有一個PlaceholderFragment,你是從其他地方獲得。

+0

教程後,他們告訴你要刪除的部分在OnCreate函數 – 2015-04-04 20:12:28

+1

@SvenB:而在這一點上,它是安全的刪除'PlaceholderFragment'。我無法推測爲什麼他們首先對「PlaceholderFragment」感到困擾,也不知道爲什麼他們沒有告訴你將它作爲重寫'onCreate()'的一部分來刪除它。但是,在引入'PlaceholderFragment'時,需要根據初始實現'onCreate()'方法。 – CommonsWare 2015-04-04 20:20:08

0

您需要此代碼,因爲在本教程中,第二個活動有一個片段。所以,活動的內容由片段的內容決定。你不能看到它在這個代碼:

if (savedInstanceState == null) { 
    getSupportFragmentManager().beginTransaction() 
     .add(R.id.container, new PlaceholderFragment()).commit(); 
} 

而片段的內容是由fragment_display_message.xml的含量。這是你發佈代碼做(電話fragment_display_message.xml):

/** 
    * 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_display_message, 
         container, false); 
       return rootView; 
     } 
    } 
} 
+0

教程後面他們告訴你刪除該部分的oncreate函數 – 2015-04-04 20:13:11

+0

Nop。該教程說你必須刪除onCreateOptionsMenu方法。這是如此不同。這是應用程序的菜單。在教程中,您不必使用它。我引用:「刪除onCreateOptionsMenu()方法。 您不需要它爲這個應用程序。」 – 2015-04-04 20:15:20

+0

但請查看下面的代碼:DisplayMessageActivity的完整onCreate()方法現在看起來像這樣: – 2015-04-04 20:16:05