我正在尝试添加一个ListView
using Fragment
。我知道可以通过扩展ListFragment
等来完成。但我想扩展Fragment
然后添加listView
. 但是下面的代码不起作用(它也没有显示任何错误)。
片段类
public class OtherFragment extends Fragment {
final String[] items = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.activity_main, container,false);
ListView list = (ListView)view.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
return view;
}
}
片段的 XML 文件
<RelativeLayout 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" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
MainActivity(主类)
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentManager fm= getFragmentManager();
if(fm.findFragmentById(R.id.fragmentContent)==null)
{
Log.d("add fragment", "fragment added");
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragmentContent, new OtherFragment());
ft.commit();
}
}
}
main.xml(主 xml 文件)
<RelativeLayout 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" >
<LinearLayout
android:id="@+id/fragmentContent"
android:layout_width="0px"
android:layout_height="match_parent"/>
</RelativeLayout>
固定的:
android:layout_width="match_parent"
丑陋的错误。谢谢尼尼尼奥