当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to allow error on Android Fragment?

问题描述:

I have an error in my code, why could happen?

error occurred on :

  • setContentView(R.layout.activity_main_menuangkot);
  • String[] array_angkot = getResources().getStringArray(R.array.array_angkot);
  • listView = (ListView) findViewById(R.id.list_angkot);
  • editSearch = (EditText) findViewById(R.id.editSearch);
  • adapter = new ArrayAdapter(this, R.layout.list_angkot,

    R.id.text_nama, array_angkot);

Her error is The method setContentView(int) is undefined for the type HomeFragment, The constructor ArrayAdapter(HomeFragment, int, int, String[]) is undefined

Please help Me ...

HomeFragment.java

public class HomeFragment extends Fragment {

private ListView listView;

private ArrayAdapter<String> adapter;

private EditText editSearch;

ArrayList<HashMap<String, String>> listNama;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// dapatkan data string array dari XML

String[] array_angkot = getResources().getStringArray(R.array.array_angkot);

// deklarasi object listview & edittext dengan layout xml

listView = (ListView) findViewById(R.id.list_angkot);

editSearch = (EditText) findViewById(R.id.editSearch);

// instansiasi arrayadapter dengan parameter (context,resource,textview

// resource,array string)

adapter = new ArrayAdapter<String>(this, R.layout.list_angkot,

R.id.text_nama, array_angkot);

网友答案:

The method setContentView is used for Activity-derived classes. When you are developing a Fragment, you never call setContentView (as the error message says, that method is undefined in a Fragment). Instead, you override onCreateView and return the root of the view hierarchy that will be used for that Fragment. As @skywall suggests, you should read the documentation for how to create a Fragment (including how to add it to an Activity). The place to start is the Guide topic on Fragments. You should also consult the documentation for the Fragment class, which includes a description of the Fragment lifecycle and the methods you may need to override.

Then you need to reorganize your code so that the process of setting up the view that you now have in onCreate occurs instead in onCreateView.

分享给朋友:
您可能感兴趣的文章:
随机阅读: