我正在创建一个应用程序。我使用了带有片段的Tablayout,使用ListFragment扩展了其中一个片段,并想在该片段中给出意图,我使用了以下内容...
home_fragment.java
package com.example.mymehnat;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class home_fragment extends ListFragment implements AdapterView.OnItemClickListener {
ListView lst;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_fragment, container, false);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(home_fragment.this.getActivity(), R.array.songs, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adapter, View view,int position, long l) {
Intent intent = new Intent(home_fragment.this.getActivity(), Lyrics.class);
intent.putExtra("SongName", lst.getItemAtPosition(position).toString());
lst.getContext().startActivity(intent);
}
}
home_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:background="@color/background">
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@android:id/list">
</ListView>
</LinearLayout>
但是每当我单击列表上的任何项目均不起作用时,什么也不显示,并提示我错误...
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.widget.ListView.getItemAtPosition(int)' on a null object reference
at com.example.mymehnat.home_fragment.onItemClick(home_fragment.java:36) and so on
请帮助我。
非常感谢您的帮助。
答案 0 :(得分:0)
您没有初始化ListView lst
尝试这样做。
这需要在OnCreateView
lst = v.findViewById(R.id.list)