So, I’ve been dealing with this for several days and simply can’t get it to work. I have an Activity that displays a fragment, and that Fragment is a member of the list of fragments that I view with the ViewPager. The fragment itself consists of a TextView and a ListView. The ListView is populated from the user adapter.
What I'm trying to do is pass the OnItemSelected event back to the Fragment where it is being processed. For me, it's probably best to just go and show the code here.
This action
public class DialogInventory extends FragmentActivity implements OnItemSelectedListener {
ViewPager viewPager;
Pager pager;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.dialog_inventory);
List<Fragment> fragList = new Vector<Fragment>();
fragList.add(Fragment.instantiate(this, FragmentOne.class.getName()));
fragList.add(Fragment.instantiate(this, FragmentTwo.class.getName()));
pager = new Pager(getSupportFragmentManager(), fragList);
viewPager = (ViewPager) findViewById(R.id.pagerMain);
viewPager.setAdapter(pager);
listMain = (ListView) findViewById(R.id.listMain);
listMain.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
switch (viewPager.getCurrentItem()) {
case 0:
FragmentOne fragOne = new FragmentOne();
fragOne.onItemSelected(parent, view, pos, id);
break;
case 1:
FragmentTwo fragTwo = new FragmentTwo();
fragTwo.onItemSelected(parent, view, pos, id);
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
This is a snippet:
public class FragmentOne extends Fragment implements OnItemSelectedListener {
View view;
ListView listMain;
ArrayList<String> invItems = new ArrayList<String>();
public FragmentOne() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle bundle) {
view = inflater.inflate(R.layout.fragment_one, viewGroup, false);
listMain = (ListView) v.findViewById(R.id.listMain);
listMain.setAdapter(new AdapterItem(getActivity().getApplicationContext(),
R.layout.tile_item, invItems));
listMain.setOnItemSelectedListener(this);
return view;
}
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Log.i("Test", "hit");
}
. , . , , , OnItemSelected Activity ... OnItemSelected . ?
: ListView ( , , ). , OnItemSelectedListener , . , , , OnItemSelectedListener.
Edit2: . , . - . OnItemSelected . , -, , , . , , . , .
, NPE . ListView, , , .