带有标签的Android ActionBar,获取多个与片段相关的错误消息

时间:2014-03-20 16:28:53

标签: android android-fragments android-context

我收到了这些错误,

The method setContentView(int) is undefined for the type DataEdit

The method getApplicationContext() is undefined for the type DataEdit

The method findViewById(int) is undefined for the type DataEdit 

代码如下:

    public class DataEdit extends Fragment {
SQLiteDatabase db;
SQLiteDatabase d;
Cursor queryAll;

@Override
public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.dataedit); 
    DBAdapter msdb= new DBAdapter(getApplicationContext(),"adfg", null);        
    db=msdb.getWritableDatabase(); 
    ((EditText)findViewById(R.id.edSpecies)).requestFocus();
}}

我在这里缺少什么?提前感谢您的耐心和智慧。

这是修改后的代码......

    public class DataEdit extends Fragment {
SQLiteDatabase db;
SQLiteDatabase d;
Cursor queryAll;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dataedit, container, false);
    DBAdapter msdb= new DBAdapter(view.getApplicationContext(),"adfg", null);        
    db=msdb.getWritableDatabase(); 
    ((EditText)view.findViewById(R.id.edSpecies)).requestFocus();
    return view;
}

1 个答案:

答案 0 :(得分:0)

Fragments的行为与Activities不同。片段中的视图层次结构在onCreateView中创建,必须重写并返回View对象。然后在膨胀的视图本身上调用findByViewId()。请参阅文档here

onCreateView()中,您会像这样夸大视图:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // your layout
    View view = inflater.inflate(R.layout.dataedit, container, false);

    // find the element in the inflated view
    ((EditText) view.findViewById(R.id.edSpecies)).requestFocus();

    // get the context from the holding activity
    DBAdapter msdb= new DBAdapter(getActivity().getApplicationContext(),"adfg", null);
    ...

    return view;

}