对于学校我正在制作一个Android应用程序.对于这个应用程序,我有一个片段,它从数据库中显示一个只有字符串的gridview.为此,我需要一个片段.当我调用getActivity()时,它返回null.该onAttach方法,如建议在这里没有得到应用程序崩溃之前调用.我该怎么解决这个问题?
weekFragmetn.xml:
package nl.siebeh.schoolmate;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class weekFragment extends Fragment {
dbLayer db;
Context mContext;
@Override
public void onAttach(Activity activity) {
mContext = getActivity();
Log.i("Schoolmate","onAttach called");
super.onAttach(activity);
}
public weekFragment newInstance(String title) {
Log.i("Schoolmate","newInstance called");
db = new dbLayer(mContext);
weekFragment fragment = new weekFragment();
ArrayList<ArrayList<Object>> result = null;
if(title == "leraren"){
result = …Run Code Online (Sandbox Code Playgroud) 我想在骨架应用程序的OnCreate()中注册一个上下文菜单:
/** Called with the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.skeleton_activity);
View v = findViewById(R.layout.skeleton_activity);
registerForContextMenu(v);
// Find the text editor view inside the layout, because we
// want to do various programmatic things with it.
mEditor = (EditText) findViewById(R.id.editor);
// Hook up button presses to the appropriate event handler.
((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);
((Button) findViewById(R.id.clear)).setOnClickListener(mClearListener);
mEditor.setText(getText(R.string.main_label));
}
Run Code Online (Sandbox Code Playgroud)
调试器告诉我findViewById(R.layout.skeleton_activity)返回null.
@CommonsWare对类似帖子的解决方案是等到onFinishInflate().但是,在他提供的示例项目中,他似乎并不等到onFinishInflate.
我的问题: