在片段中列出

时间:2014-01-17 11:53:12

标签: android listview android-fragments

我在片段中遇到listview的问题。 我想在片段中显示一个带有水果的列表,但尝试了一些事情。 在更高版本中,String[]应包含来自json对象的数据。

这是当前状态:

public class fragmentA extends Fragment
    implements View.OnClickListener {

TextView textView;
ViewStub viewStub;
ListFragment listView;

static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
        "Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
        "Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle  savedInstanceState) {
     // das Layout fuer dieses Fragment laden
     View view= inflater.inflate(R.layout.fragmenta, container, false);
     // inflate layout
     Button notfallbtn = (Button) view.findViewById(R.id.notfallbtn);

    textView = (TextView) view.findViewById(R.id.textView);
   // listView = (ListFragment) view.findViewById(R.id.einkaufsliste);
    viewStub = (ViewStub) view.findViewById(R.id.viewStub);
    viewStub.setVisibility(View.GONE);
    // initialize button using the inflated view object
    notfallbtn.setOnClickListener(this);
    // listener for button

   setListAdapter(new ArrayAdapter<String>(this, R.layout.einkaufsliste,FRUITS));

   ListView listView = getListView();
   listView.setTextFilterEnabled(true);

   listView.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent, View view,
                               int position, long id) {
           // When clicked, show a toast with the TextView text
           Toast.makeText(getApplicationContext(),
                   ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
       }
   });


    return view;   // return inflated view
 }

我得到的错误消息:

  

无法解析'setListAdapter'

     

无法解析'einkaufsliste'

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

public class fragmentA extends Fragment

不会延伸ListFragmentsetListAdapterListFragment的方法。

http://developer.android.com/reference/android/app/ListFragment.html

你也可能需要

new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,FRUITS)

而不是this使用getActivity()来返回与此片段相关联的活动。

同时阅读

http://developer.android.com/reference/android/app/ListActivity.html

还覆盖onActivityCreated并使用ListView lv = getListView()