public class ShowActivity extends Activity implements OnClickListener{
private LinearLayout llaouyBase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboardactivity);
llaouyBase = (LinearLayout) findViewById(R.id.llaouyBase);
Button t;
for(int i=0;i<5;i++) {
t= new Button(ShowActivity.this);
t.setId(i);
t.setOnClickListener(this);
llaouyBase.addView(t, i);
}
}
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
v.getId(), 8000).show();
}
}
這是我的活動,在佈局中我有一個空白的線性佈局,方向垂直。我試圖添加5個按鈕,我可以成功地做。如何添加點擊這些按鈕的事件?當運行這個,即時獲取資源找不到異常。如何爲動態添加的按鈕添加點擊事件
07-04 12:22:07.535: E/AndroidRuntime(20957): FATAL EXCEPTION: main
07-04 12:22:07.535: E/AndroidRuntime(20957): android.content.res.Resources$NotFoundException: String resource ID #0x3
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.content.res.Resources.getText(Resources.java:233)
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.widget.Toast.makeText(Toast.java:265)
07-04 12:22:07.535: E/AndroidRuntime(20957): at com.example.testapp.ShowActivity.onClick(ShowActivity.java:55)
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.view.View.performClick(View.java:4103)
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.view.View$PerformClick.run(View.java:17117)
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.os.Handler.handleCallback(Handler.java:615)
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.os.Handler.dispatchMessage(Handler.java:92)
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.os.Looper.loop(Looper.java:137)
07-04 12:22:07.535: E/AndroidRuntime(20957): at android.app.ActivityThread.main(ActivityThread.java:4744)
07-04 12:22:07.535: E/AndroidRuntime(20957): at java.lang.reflect.Method.invokeNative(Native Method)
07-04 12:22:07.535: E/AndroidRuntime(20957): at java.lang.reflect.Method.invoke(Method.java:511)
07-04 12:22:07.535: E/AndroidRuntime(20957): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-04 12:22:07.535: E/AndroidRuntime(20957): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-04 12:22:07.535: E/AndroidRuntime(20957): at dalvik.system.NativeStart.main(Native Method)
我跟着這個鏈接給下面。我在這段代碼中缺少什麼?
How to identify the button clicked from a dynamically generated table
總是很快。打我吧:) – Raghunandan
:)我覺得同樣的東西 – Blackbelt