I need to get the position of the grid view in the onItemClick
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, TabActivity.class);
startActivity(i);
Position = 0;
break;
case 1:
i = new Intent(MainActivity.this, TabActivity.class);
startActivity(i);
Position = 1;
break;
case 2:
i = new Intent(MainActivity.this, TabActivity.class);
startActivity(i);
Position = 2;
break;
case 3:
i = new Intent(MainActivity.this, TabActivity.class);
startActivity(i);
Position = 3;
break;
case 4:
i = new Intent(MainActivity.this, TabActivity.class);
startActivity(i);
Position = 4;
break;
}
}
});
and use it in a different Fragment class in a switch loop
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_city, container, false);
int position = new MainActivity().Position;
ArrayList<CityScreenItem> city = new ArrayList<>();
switch (position) {
case 0:
city.add(new CityScreenItem("Giza", "Giza is good",
R.drawable.dubai));
break;
case 1:
city.add(new CityScreenItem("Dubai", "Dubai is good",
R.drawable.egypt));
break;
}
CityScreenAdapter adapter = new CityScreenAdapter(getActivity(), city);
ListView listView = rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
return rootView;
}
but it always displays the first case when I check this was due to the int position = new MainActivity().Position;
code but I could not find the answer. Note I did make a public int for Position at the beginning of the class
You are creating a new object every time:
int position = new MainActivity().Position;
This will reset the position to what you are setting it to. Make Position static.
public static int POSITION = 0;
This should fix your problem. Access it like below:
int position = MainActivity.POSITION;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.