2017-04-01 77 views
-1

我想在從抽屜中單擊列表項目時調用新的活動。我在互聯網上搜索,我得到的是調用該活動的片段。所以,我想知道如何製作一個活動的片段。如何在android studio中創建一個活動的片段?

P.S.-對不起,如果這個問題很愚蠢。我仍然是一個小菜鳥。

+0

我不明白你到底在問什麼? – Remario

+0

我想在抽屜中按下列表項時調用一個活動。所以,我想知道我們該怎麼做。 @CaspainCaldion –

回答

0

片段表示活動中的行爲或用戶界面的一部分。您可以在單個活動中組合多個片段來構建多窗格用戶界面,並在多個活動中重用片段。 Here來自android官方開發者指南的完整說明。

同樣在android開發人員指南中,您可以找到code以正確創建和使用片段。

創建一個片段類:

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.ViewGroup; 

public class ExampleFragment extends Fragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.example_view, container, false); 
    } 
} 

然後,你必須將片段添加到活動佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <fragment android:name="com.example.android.fragments.HeadlinesFragment" 
       android:id="@+id/headlines_fragment" 
       android:layout_weight="1" 
       android:layout_width="0dp" 
       android:layout_height="match_parent" /> 

    <fragment android:name="com.example.android.fragments.ExampleFragment" 
       android:id="@+id/example_fragment" 
       android:layout_weight="2" 
       android:layout_width="0dp" 
       android:layout_height="match_parent" /> 

</LinearLayout> 

最後,你可以佈局添加到您的活動:

import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 

public class MainActivity extends FragmentActivity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.item_from_exampleLayout); 
    } 
} 

我從上面提到的android開發者指南中拿了那些例子。


無論如何,如果我明白你的問題該代碼應工作:使用意圖被點擊列表項時

list.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){ 

      Intent intent = new Intent(ThisClass.this, ClassToCall.class); 
      startActivity(intent); 

    } 
}); 

這將啓動一個新的活動,但它並不需要的片段。

相關問題