First of all, add the following dependencies to build.gradle in app, banner is the frame of carousel chart, glide is the frame of picture loading.
implementation 'com.youth.banner:banner:1.4.9' implementation 'com.github.bumptech.glide:glide:4.7.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1' //The following dependency okhttp and okhttputil are used for network requests implementation 'com.squareup.okhttp3:okhttp:4.3.0' implementation 'com.squareup.okio:okio:2.4.3' implementation 'com.zhy:okhttputils:2.6.2'
Then write the layout that needs to use the rotation chart. Please modify it according to your own project requirements. A simple example is as follows:
<com.youth.banner.Banner android:id="@+id/banner" android:layout_width="match_parent" android:layout_height="180dp" />
Due to the different scale requirements of different project rotation chart, it is recommended not to write in the layout file. In my example later, I will use code to dynamically change the aspect ratio of banner control.
After that, I will deal with the business logic flow of the carousel chart: ① when opening the APP, I will get the carousel chart data json obtained by the last request server from SharedPreferences and load it. If SharedPreferences has no data, I will manually write the default data. ② Request the server to obtain the latest data of the carousel chart, and save the obtained json to SharedPreferences after successful request. ③ Analyze the new data requested and update the carousel chart
Next, I will post all the codes related to banner directly, and the important parts will be explained in the notes:
First add the following required global variables:
private Banner banner; private ArrayList<String> list_path; private ArrayList<String> list_title; private ArrayList<String> list_href;
And the class needs to inherit OnBannerListener to set the click event:
public class BannerDemo extends AppCompatActivity implements OnBannerListener
Then set the width height ratio of banner control and call the initialization and update methods in oncreate method:
banner = (Banner)findViewById(R.id.banner); WindowManager wm1 = getActivity().getWindowManager(); int width = wm1.getDefaultDisplay().getWidth(); LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) banner.getLayoutParams(); linearParams.width = width; linearParams.height = width*9/16; banner.setLayoutParams(linearParams); //Set the carousel control to a 16 / 9 scale initView(); updateBanner();
Finally, complete the initialization and update methods and set the click event:
private void updateBanner(){ String host = new Defines().SERVER_HOST+"getBanner"; OkHttpUtils .post() .url(host) .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { Toasty.error(getActivity(), "Server request failed", Toast.LENGTH_SHORT, true).show(); } @Override public void onResponse(String response, int id) { try { JSONObject jsonObject = new JSONObject(response); int code = jsonObject.getInt("code"); if (code==200) { //If the request is successful, clear the current data, write it back and save it to SharedPreferences list_path.clear(); list_href.clear(); list_title.clear(); JSONArray dataArray = jsonObject.getJSONArray("data"); final SharedPreferences sp = getActivity().getSharedPreferences("banner", Context.MODE_PRIVATE); sp.edit().putString("jsonList",dataArray.toString()).commit(); ArrayList<String> update_list_path = new ArrayList<>(); ArrayList<String> update_list_title = new ArrayList<>(); ArrayList<String> update_list_href = new ArrayList<>(); if(dataArray.length()!=0){ for(int i=0;i<dataArray.length();i++){ JSONObject thisBanner = dataArray.getJSONObject(i); update_list_title.add(thisBanner.getString("title")); update_list_path.add(thisBanner.getString("img_url")); update_list_href.add(thisBanner.getString("href")); } }else{ update_list_title.add("No_Banner_Title"); update_list_path.add("No_Banner_Url"); update_list_href.add("No_Banner_Href"); } list_path = update_list_path; list_title = update_list_title; list_href = update_list_href; //Note that the global variable parameter cannot be used in the update method of banner. Update list path and update list title are all redefined variables banner.update(update_list_path,update_list_title); } else { Toasty.error(getActivity(),jsonObject.getString("msg"), Toast.LENGTH_SHORT, true).show(); } } catch (JSONException e) { e.printStackTrace(); Toasty.error(getActivity(),"Failed to get the rotation chart",Toast.LENGTH_LONG).show(); } } }); } private void initView(){ //Set of place picture addresses list_path = new ArrayList<>(); //Set of titles list_title = new ArrayList<>(); //Put linked collection list_href = new ArrayList<>(); final SharedPreferences sp = getActivity().getSharedPreferences("banner", Context.MODE_PRIVATE); try { String bannerArrayJson = sp.getString("jsonList",null); if(bannerArrayJson!=null){ JSONArray dataArray = new JSONArray(bannerArrayJson); if(dataArray.length()!=0){ for(int i=0;i<dataArray.length();i++){ JSONObject thisBanner = dataArray.getJSONObject(i); list_title.add(thisBanner.getString("title")); list_path.add(thisBanner.getString("img_url")); list_href.add(thisBanner.getString("href")); } }else{ list_path.add("No_Banner_Url"); list_title.add("No_Banner_Title"); list_href.add("No_Banner_Href"); } }else{ list_path.add("No_Banner_Url"); list_title.add("No_Banner_Title"); list_href.add("No_Banner_Href"); } } catch (JSONException e) { } //Set the built-in style. There are six ways to click in one by one. banner.setBannerStyle(2); //Set picture loader, picture loader is below banner.setImageLoader(new MyLoader()); //Set picture web address or collection of addresses banner.setImages(list_path); //Set the animation effect of the carousel, including a variety of special effects, which can be found in the method and experienced one by one banner.setBannerAnimation(Transformer.DepthPage); //Set the title set of the carousel banner.setBannerTitles(list_title); //Set rotation interval banner.setDelayTime(3000); //Set whether it is auto rotation. The default is yes. banner.isAutoPlay(true); //Set the position of the indicator, small dot, left middle right. banner.setIndicatorGravity(BannerConfig.CENTER) //The above content can be written as a chain layout, which is the monitoring of the carousel chart. More important. The method is below. .setOnBannerListener(this) //The last call method must be invoked to start the chart. .start(); } //Set click event @Override public void OnBannerClick(int position) { if(!list_href.get(position).equals("No_Banner_Href")){ Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(list_href.get(position))); startActivity(intent); }else{ Toasty.info(getActivity(),"Failed to load the carousel chart",Toast.LENGTH_SHORT).show(); } } //The user-defined image loader uses glide to load images. The placeholder and error are the bitmap of loading and loading failure respectively private class MyLoader extends ImageLoader { @Override public void displayImage(Context context, Object path, ImageView imageView) { RequestOptions options = RequestOptions.centerInsideTransform().placeholder(R.drawable.loadingbanner).error(R.drawable.loadingbanner); Glide.with(context).load((String) path).apply(options).into(imageView); } }