Android 自定义适配器无法应用于导航抽屉';s片段
我想在导航抽屉的片段页面中显示自定义listview。然而,在我的fragment类中,我遇到了一个错误,似乎我无法设置自定义适配器Android 自定义适配器无法应用于导航抽屉';s片段,android,listview,android-fragments,Android,Listview,Android Fragments,我想在导航抽屉的片段页面中显示自定义listview。然而,在我的fragment类中,我遇到了一个错误,似乎我无法设置自定义适配器 package android_gcm_client.mynavigation; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInfla
package android_gcm_client.mynavigation;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
public class List_Fragment extends Fragment {
View rootview;
ArrayList prgmName;
public static int [] prgmImages= {R.drawable.images,R.drawable.images1,R.drawable.images2,R.drawable.images3,R.drawable.images4,R.drawable.images5,R.drawable.images6,R.drawable.images7,R.drawable.images8};
public static String [] prgmNameList={"Let Us C","c++","JAVA","Jsp","Microsoft .Net","Android","PHP","Jquery","JavaScript"};
@Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview=inflater.inflate(R.layout.custom_layout,container,false);
CustomAdapter ca = new CustomAdapter(this,prgmNameList,prgmImages);
ListView listview=(ListView) getView().findViewById(R.id.listView);
listview.setAdapter(ca);
return rootview;
}
}
错误似乎发生在下面的行中(无法应用自定义适配器)
在MainActivity中,我按如下方式调用片段:
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment objFragment=null;
switch(position) {
case 0:
objFragment=new ListFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
我尝试了不同的方法来显示导航项所选方法的自定义listview
我试图直接调用activity而不是fragment,但问题是导航抽屉对于所有活动都不可见。所以我尝试在活动中调用CustomAdapter,就像在片段中一样
我一直在努力解决这个错误。(很抱歉英语不好)。您正在自定义适配器中使用此
。通常适配器需要构造函数调用中的上下文。但是这个构造函数是在片段内部调用的,this
不能使用
您可以使用getActivity()
作为片段内的上下文但是。
有时,如果在这个片段的onAttach()
之前调用它,它可能会返回一个null
CustomAdapter ca = new CustomAdapter(getActivity(), prgmNameList, prgmImages);
您还可以通过在应用程序类中创建静态变量来使用应用程序上下文:
public class Application extends android.app.Application {
public static Context AppContext = null;
@Override
public void onCreate() {
super.onCreate();
AppContext = getApplicationContext();
// You can use this line to solve styling problems
// because Manifest android:theme is not working
AppContext.setTheme(R.style.AppTheme);
}
}
并创建如下适配器:
CustomAdapter ca = new CustomAdapter(Application.AppContext, prgmNameList, prgmImages);
请分享您收到的确切错误。另外,您是否创建了CustomAdapter.java类?这个类在纯Android中不存在。所以,你必须创造它。
CustomAdapter ca = new CustomAdapter(Application.AppContext, prgmNameList, prgmImages);