ListFragment实例

ListFragment实例_第1张图片

首先创建我们的Fragment部分的文件

fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <ListView android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

</LinearLayout>

FragmentTest.java

package com.example.listfragmenttest;

import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainFragment extends ListFragment{


String cars[]={
"奔驰",
"宝马",
"奥迪",
"大众"
};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

return inflater.inflate(R.layout.fragment, container, false);
}

@SuppressLint("ShowToast")
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "您点击了"+cars[position], Toast.LENGTH_LONG).show();
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cars));
}
}

activity_main.xml

<LinearLayout 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"
    tools:context=".MainActivity" 
    android:orientation="horizontal">

    <fragment android:name="com.example.listfragmenttest.MainFragment"
        android:id="@+id/fragment1"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:layout_weight="1"/>
    
    <fragment android:name="com.example.listfragmenttest.MainFragment"
        android:id="@+id/fragment2"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:layout_weight="2"/>
  
</LinearLayout>

MainActivity.java

package com.example.listfragmenttest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

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

你可能感兴趣的:(listfragment)