作業:用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; } } }; }