如何快速創造100個 Button / ImageView 並進行監聽
比如需要顯示100 個按鈕,難道我們真的就要佈局文件中寫100個按鈕的程式碼嗎?
不!學程式的人一定要會偷懶的方法!
我們其實可以利用for循環一次創建 100 個按鈕,其實你們都想的到這個方法,只是不知如何著手,在此,我將一步一步實作,大家一起學習學習。
佈局文件main.xml的代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:scrollbars="vertical"
android:fadingEdge="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:id="@+id/linearLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</LinearLayout>
</ScrollView>
ButtonsActivity.java程式碼如下:
public class ButtonsActivity extends Activity
{
private LinearLayout linearLayout;
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//取得main佈局的物件id,並進行監聽
linearLayout = (LinearLayout)findViewById(R.id.linearLayout);
/*
* 使用一個for回圈, 在LinearLayout中增加100個按鈕
*/
for(int i=1; i<=100;i++)
{
//創造一個新的Button
Button btnLesson =new Button(this);
//設置對象id
btnLesson.setId(i);
//設置對象顯示的值
btnLesson.setText("Lesson"+i);
//給按鈕增加監聽事件
btnLesson.setOnClickListener(new btnListener(btnLesson));
//將Button對象添加到LinearLayout中
linearLayout.addView(btnLesson);
}
}
/*
* 增加一個按鈕監聽器, 用來點擊按鈕後改變按鈕名稱
*/
class btnListener implements OnClickListener
{
private Button btn;
/*
* 一個構造方法, 將Button作為參數
*/
private btnListener(Button btn)
{
this.btn = btn;//將引用變數傳遞給實體變數
}
publicvoid onClick(View v)
{
btn.setText("Welcome!");//改變按鈕名稱
}
}
}
執行結果:
沒有留言:
張貼留言