从需要视图的主活动中调用片段中定义的函数

时间:2016-06-17 14:23:49

标签: android view fragment

我在片段catch中有一个函数,它使用查询的输出动态更改其cardView。 我第一次从那个片段调用它并且它有效。我第二次从(Frag_Lista)调用它,但我无法正确设置第二个参数main activity

Frag_Lista

view

}

public void function_in_fragment() {
//some code
Context context = getActivity();
DBhelper database = ((MainActivity)getActivity()).getDatabase();
Cursor cursor=database.ottieni_tutto();
genera_lista(cursor,getView());

}

MainActivity

public void genera_lista(Cursor cursor, View v) {
    list.clear();
    if(cursor!=null) {
        if(cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                //Log.d(TAG,cursor.getString(cursor.getColumnIndex(DBhelper.COL_NOME)));
                String nome = cursor.getString(cursor.getColumnIndex(DBhelper.COL_NOME));
                String tipo = cursor.getString(cursor.getColumnIndex(DBhelper.COL_TIPO));
                String difficolta = cursor.getString(cursor.getColumnIndex(DBhelper.COL_DIFFICOLTA));
                String immagine = cursor.getString(cursor.getColumnIndex(DBhelper.COL_IMMAGINE));
                Food_Card food_card = new Food_Card(immagine, nome, tipo, difficolta);
                list.add(food_card);
                cursor.moveToNext();
            }
            cursor.close();
        }
        else Log.d(TAG,"Cursor vuoto");
    }
    else Log.d(TAG,"Cursor nullo");

    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    adapter=new food_adapter(getActivity(),list);
    recyclerView.setAdapter(adapter);

}

如何正确传递当前视图?

Frag_Lista

public void function_in_mainActivity(String[] parametri) {
Cursor cursor=database.query_filtri(parametri);
Frag_Lista nothing=new Frag_Lista();
View v= ?
nothing.genera_lista(cursor,v);

1 个答案:

答案 0 :(得分:0)

像这样更改onCreateView

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.frag_lista, container, false);
    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
    setHasOptionsMenu(true);
    return(v);
}

Fragment recyclerView内为RecyclerView创建一个字段。

现在你总是引用public void genera_lista(Cursor cursor) 并且不需要将它作为参数传递给方法。

A