作业:用TextView 添加图片:创建一个按键,按键按下时就切换一张图片,总共有5张图片
1、在资源文件夹中加入图片
2、实现如下代码
public class MainActivity extends AppCompatActivity { TextView tx; Button bt1; int a; ImageSpan span1,span2,span3,span4,span5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tx = (TextView) findViewById(R.id.textView1); bt1 = (Button)findViewById(R.id.button); a= 1; span1 = new ImageSpan(this, R.mipmap.dangao1); span2 = new ImageSpan(this, R.mipmap.daogao2); span3 = new ImageSpan(this, R.mipmap.dangao3); span4 = new ImageSpan(this, R.mipmap.dangao4); span5 = new ImageSpan(this, R.mipmap.dangao5); SpannableString spanStr = new SpannableString(" "); spanStr.setSpan(span1, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tx.setText(spanStr ); a++; bt1.setOnClickListener(listener1);//给BT1创建一个监听器} } Button.OnClickListener listener1 = new Button.OnClickListener(){//创建监听对象 public void onClick(View v){ //监听器里需要做的事 if(a==2) { SpannableString spanStr = new SpannableString(" "); spanStr.setSpan(span2, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tx.setText(spanStr ); a++; } else if(a==3) { SpannableString spanStr = new SpannableString(" "); spanStr.setSpan(span3, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tx.setText(spanStr ); a++; } else if(a==4) { SpannableString spanStr = new SpannableString(" "); spanStr.setSpan(span4, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tx.setText(spanStr ); a++; } else if(a==5) { SpannableString spanStr = new SpannableString(" "); spanStr.setSpan(span5, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tx.setText(spanStr ); a++; } else if(a==6) { SpannableString spanStr = new SpannableString(" "); spanStr.setSpan(span1, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tx.setText(spanStr ); a=2; } } }; }
时间: 2024-11-10 15:08:04