我正在尝试将listview实现为fragment.But我的应用程序崩溃在这里是我的片段代码
public class ConversationFragment extends Fragment {
public View rootView=null;
private ListView lv;
private ArrayList<String> strArr;
private ArrayAdapter<String> adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String name = getArguments().getString("name");
rootView = inflater.inflate(R.layout.fragment_conversation, container, false);
TextView username=(TextView)rootView.findViewById(R.id.user_name);
username.setText(name);
strArr=new ArrayList<String>();
adapter=new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1,strArr);
lv.setAdapter(adapter);
rootView.findViewById(R.id.get_from_user).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.get_from_user) {
getFromUser(v);
}
}
});
return rootView;
}
这是片段布局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"
android:background="#878787" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="dfgdfgdf"
android:textSize="20dp"
android:layout_centerInParent="true"
android:id="@+id/user_name"/>
<EditText
android:id="@+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/get_from_user"
android:text="Gönder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
/>
<ListView
android:id="@+id/message_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
还有logcat:http://prntscr.com/4a5svo
我该如何解决?你有什么建议?
答案 0 :(得分:1)
未设置lv值。在lv上添加findviewbyid的代码你应该是好的
答案 1 :(得分:1)
像对Textview一样初始化Listview lv,并确保strArr
不为空
TextView username=(TextView)rootView.findViewById(R.id.user_name);