![](/img/trans.png)
[英]Android Spinner onItemSelected not being called inside Fragment
[英]How to refresh fragment on spinner onItemSelected in android
我有一個帶有微調器和listview的片段,當用戶從微調器中選擇一個選項時,列表視圖會更新,並且我想到一個想法,當選擇一個選項時,我必須刷新該片段。 但是問題是當我從“ onItemSelected”刷新片段時片段進入無限循環,所以我做了一個“ refreshFragment方法”來解決該問題,但是現在用戶選擇一個選項后,微調器中的第一個選項不會刷新再次執行該片段操作,除第一個選項外,其他所有選項均正常運行,因為我沒有在該選項中添加“ refreshFragment方法”,因為如果添加該選項,它將再次進入無限循環。 對不起,我的英語不好,因此我總是不贊成。
public class MatchesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemSelectedListener {
private RecyclerView recyclerView;
private MatchAdapter matchAdapter;
private ArrayList<Matches> matchCollection;
SwipeRefreshLayout mSwipeRefreshLayout;
String apiLink;
String apiType = "1";
public MatchesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_matches, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swiperefresh);
mSwipeRefreshLayout.setOnRefreshListener(this);
if (getArguments() != null) {
Bundle arguments = getArguments();
apiLink = arguments.getString("ApiLink");
apiType = arguments.getString("apiType");
Toast.makeText(getContext().getApplicationContext(), apiType, Toast.LENGTH_LONG).show();
}else {
apiLink = "http://first-api-link";
Toast.makeText(getContext().getApplicationContext(), "nothing", Toast.LENGTH_LONG).show();
}
Spinner spinner = (Spinner) getView().findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
ConnectivityManager cm = (ConnectivityManager) getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
String answer = "Internet";
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
answer="You are connected to a WiFi Network";
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
answer="You are connected to a Mobile Network";
init();
new FetchDataTask().execute();
}
else {
answer = "No internet Connectivity";
Toast.makeText(getContext().getApplicationContext(), answer, Toast.LENGTH_LONG).show();
}
}
private void init() {
recyclerView = (RecyclerView) getActivity().findViewById(R.id.matchesRecyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
matchCollection = new ArrayList<>();
matchAdapter = new MatchAdapter(matchCollection, getActivity());
recyclerView.setAdapter(matchAdapter);
}
@Override
public void onRefresh() {
init();
new FetchDataTask().execute();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
apiLink = "http://first-api-link";
switch (position){
//can't add refreshFragment in here it makes infinity lopp
case 0: apiLink = "first-api-link";
break;
case 1:
refreshFragment("second-api-link", 2);
break;
case 2:
refreshFragment("third-api-link", 3);
break;
case 3:
refreshFragment("fourth-api-link", 4);
break;
case 4:
refreshFragment("fifth-api-link", 5);
break;
case 5:
refreshFragment("sixth-api-link", 6);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class FetchDataTask extends AsyncTask<Void, Void, Void> {
private String mZomatoString;
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
Uri builtUri = Uri.parse(apiLink);
URL url;
try {
url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("user-key", "acfd3e623c5f01289bd87aaaff1926c1");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
//Nothing to do
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
mZomatoString = buffer.toString();
JSONObject jsonObject = new JSONObject(mZomatoString);
Log.v("Response", jsonObject.toString());
JSONArray matchArray = jsonObject.getJSONArray("data");
//list = new ArrayList<>();
for (int i = 0; i < matchArray.length(); i++) {
Log.v("BRAD_", i + "");
String home_team;
String away_team;
String home_flag;
String away_flag;
JSONObject jTeam = (JSONObject) matchArray.get(i);
if (apiType == "1"){
JSONObject jHomeTeam = (JSONObject) jTeam.getJSONObject("home_team");
JSONObject jAwayTeam = (JSONObject) jTeam.getJSONObject("away_team");
//get data's from json sent from link
home_team = jHomeTeam.getString("name");
away_team = jAwayTeam.getString("name");
home_flag = jHomeTeam.getString("flag");
away_flag = jAwayTeam.getString("flag");
}else{
//get data's from json sent from link
home_team = jTeam.getString("home_team");
away_team = jTeam.getString("away_team");
home_flag = "https://www.countries-ofthe-world.com/flags-normal/flag-of-Russia.png";
away_flag = "https://www.countries-ofthe-world.com/flags-normal/flag-of-Russia.png";
}
Matches matches = new Matches();
matches.setHome_team(home_team);
matches.setAway_team(away_team);
matches.setHome_flag(home_flag);
matches.setAway_flag(away_flag);
matchCollection.add(matches);
// Stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
matchAdapter.notifyDataSetChanged();
}
}
public void refreshFragment(String apiLinks, int apiType){
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MatchesFragment fragment = new MatchesFragment();
Bundle args = new Bundle();
args.putString("ApiLink", apiLinks);
args.putString("apiType", String.valueOf(apiType));
fragment.setArguments(args);
fragmentTransaction.replace(R.id.linearfr, fragment);
fragmentTransaction.commit();
}
}
這些是與微調器一起使用時要考慮的幾件事。 它始終具有選定的值,並且選定的默認值是第一個。 因此,創建片段時,將選擇微調器中的第一個值。
當您手動打開下拉菜單並第一次選擇第一個項目時,當前默認情況下處於選中狀態,因此不會觸發您的選擇,因此不會調用刷新。 技巧是將虛擬項添加為第一個項,並忽略onClick中的位置0(您已經在執行此操作)。
之所以發生無限循環,是因為在創建視圖時微調器默認情況下選擇了第一項,因此觸發了位置為0的onClick,該調用再次調用刷新,更改片段,創建了新的微調器,選擇了第一項,並且惡性循環繼續。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.