我在活动中有一个带有ListView的片段。但是当我运行应用程序时,ListView没有显示,而是只显示一个空白活动。问题是什么? 这些是文件:
这是MainActivity.java:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_fragment);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity, menu);
return true;
}
}
ListFragment.java:
public class ListFragment extends Fragment{
ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
list = (ListView) inflater.inflate(R.layout.list_fragment, container, false);
list.setAdapter(new MyAdapter(getActivity()));
return list;
}
}
activity_main.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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<fragment class="com.dandvrn.ListFragment"
android:id="@+id/list_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
list_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
答案 0 :(得分:1)
您向xml中的片段提供android:layout_width="0dp"
,尝试给出尺寸&gt; 0
答案 1 :(得分:0)
进行以下更改:
1)您必须将活动的内容视图设置为活动的布局,而不是片段的布局:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // here
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity, menu);
return true;
}
}
2)onCreateView
应该返回您的片段视图。另外,请执行以下操作以正确访问ListView:
public class ListFragment extends Fragment {
ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_fragment, container, false);
list = (ListView) v.findViewById(R.id.list);
list.setAdapter(new MyAdapter(getActivity()));
return v;
}
希望它会对你有所帮助! : - )