最近一直有点忙,刚刚看到一个朋友的留言提到Fragment中加载ListView的问题,这里写了一个非常简单的测试,至于对Fragment的增、删、改实现动态布局构建灵活的UI,以后有时间在讨论:
MainActivity:
package com.home.testfragment; import java.util.ArrayList;
import java.util.List; import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView; public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.fragment__first_list);
List<String> list = new ArrayList<String>();
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}
}
FirstFragment:
package com.home.testfragment; import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <fragment
android:name="com.home.testfragment.FirstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="@+id/main_fragment_first" /> </LinearLayout>
fragment_first:
<?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" > <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="测试fragment的简单使用"
android:textSize="20sp" /> <ListView
android:id="@+id/fragment__first_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView> </LinearLayout>
附上界面效果: