我正在尝试用这段代码中Drawable中的图像替换颜色。 我在本教程中找到了有关如何使用Android Studio上的viewpager制作自动图像滑块的教程,但是这段代码是要切换颜色图像,如何用图像替换这种颜色?
这是我的 SliderAdapter.java
public class SliderAdapter extends PagerAdapter {
private Context context;
private List<Integer> color;
private List<String> colorName;
public SliderAdapter(Context context, List<Integer> color, List<String> colorName) {
this.context = context;
this.color = color;
this.colorName = colorName;
}
@Override
public int getCount() {
return color.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_slider, null);
TextView textView = (TextView) view.findViewById(R.id.textView);
LinearLayout linearLayout = (LinearLayout)
view.findViewById(R.id.linearLayout);
textView.setText(colorName.get(position));
linearLayout.setBackgroundColor(color.get(position));
ViewPager viewPager = (ViewPager) container;
viewPager.addView(view, 0);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager viewPager = (ViewPager) container;
View view = (View) object;
viewPager.removeView(view);
}
}
这是我的 MainActivity
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
TabLayout indicator;
List<Integer> color;
List<String> colorName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
viewPager=(ViewPager)findViewById(R.layout.viewPager);
indicator=(TabLayout)findViewById(R.layout.indicator);
color = new ArrayList<>();
color.add(Color.RED);
color.add(Color.GREEN);
color.add(Color.BLUE);
colorName = new ArrayList<>();
colorName.add("RED");
colorName.add("GREEN");
colorName.add("BLUE");
viewPager.setAdapter(new SliderAdapterDemo(this, color, colorName));
indicator.setupWithViewPager(viewPager, true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000);
}
private class SliderTimer extends TimerTask {
@Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (viewPager.getCurrentItem() < color.size() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
答案 0 :(得分:0)