如何在android studio中创建一个活动的片段?

问题描述:

我想在从抽屉中单击列表项目时调用新的活动。我在互联网上搜索,我得到的是调用该活动的片段。所以,我想知道如何制作一个活动的片段。如何在android studio中创建一个活动的片段?

P.S.-对不起,如果这个问题很愚蠢。我仍然是一个小菜鸟。

+0

我不明白你到底在问什么? – Remario

+0

我想在抽屉中按下列表项时调用一个活动。所以,我想知道我们该怎么做。 @CaspainCaldion –

片段表示活动中的行为或用户界面的一部分。您可以在单个活动中组合多个片段来构建多窗格用户界面,并在多个活动中重用片段。 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); 

    } 
}); 

这将启动一个新的活动,但它并不需要的片段。