无法访问ListFragment

时间:2014-12-07 02:15:21

标签: java android android-listfragment

我有像这样的MainActivity

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
} }

和这个

public class MyListFragment extends ListFragment implements OnItemClickListener {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.list_fragment, container, false);

    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);

    setListAdapter(adapter);
    getListView().setOnItemClickListener(this);
    int count = getListView().getCount();
    getListView().setSelection(getListView().getCount() - 1);


    test();

}

public void test(){
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);

    setListAdapter(adapter);
    getListView().setOnItemClickListener(this);
    int count = getListView().getCount();
    getListView().setSelection(getListView().getCount() - 1);
    Toast.makeText(getActivity(), "ccc"+count, Toast.LENGTH_SHORT)
            .show();

}


@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {

    Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT)
            .show();

} }

activity_main.xml有一个

fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.example.mike.mqtt.MyListFragment"
    android:id="@+id/fragment_content" />

当应用程序启动时,我会让fragment_content填满一些行。 如何从onCreate中的MainActivity.java中访问ListFragment(MyListFragment.java)。 当我按下按钮时,获取ListFragment内容计数,并将焦点设置在列表的末尾。

我不知道。谢谢。

2 个答案:

答案 0 :(得分:0)

MyListFragment fragment = (MyListFragment) getFragmentManager().findFragmentById(R.id.fragment_content)

答案 1 :(得分:0)

我避免在XML中使用片段,因为它允许我在运行中替换它们。我通常使用这样的东西:

private MyListFragment mListFragment;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // the usual business

  FragmentManager fm = getSupportFragmentManager();
  if (savedInstanceState == null) {
    // the activity opened for the first time, we create and commit fragment
    mListFragment = new MyListFragment();
    fm.beginTransaction().replace(android.R.id.content, f).commit);
  } else {
    // activity is recreating so it's safe to find already added fragments
    mListFragment = fm.findFragmentById(android.R.id.content);
  }

}