我在网站上关注了类似的问题,但没有人解决我的问题。我只是得到一行我的listview应该在片段中。我已经在添加片段之前在Activity中创建了适配器。请帮忙。
public class Frag1 extends Fragment
{
ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment, container, false);
listView = (ListView) view.findViewById(R.id.list_view);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
listView.setAdapter(FragActivity.adapter);
}
}
活动的onCreate()方法
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
adapter = new CustomAdapter(this, R.layout.List_viewit, arr);
if (savedInstanceState == null)
{
getFragmentManager()
.beginTransaction()
.add(R.id.container, new Frag1())
.commit();
}
}
适配器是CustomAdapter类扩展ArrayAdapter。列表视图在活动时显示数据,但在我尝试在片段中实现时不显示。数组arr非零。
答案 0 :(得分:0)
你能做到吗?
你的FragmentActivity
BaseAdapter mAdapter;
public BaseAdapter getmAdapter() {
return mAdapter;
}
你的片段类
YourFragmentActivity mActivity;
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mActivity = ((YourFragmentActivity) activity);
} catch (ClassCastException ex) {
ex.printStackTrace();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setAdapter(mActivity.getmAdapter());
}
答案 1 :(得分:0)
请勿拨打listView.setAdapter(FragActivity.adapter);
在OnActivityCreate()
方法中。在onCreatview
或每当片段对使用可见时调用。
答案 2 :(得分:0)
将FragActivity类中的适配器声明为static。像这样的东西
public static CustomAdapter adapter;