我已经在Layout中以编程方式创建了一个按钮,但是现在找不到捕捉onClick事件的方法。 代码如下:
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener {
int wrapContent = LinearLayout.LayoutParams.WRAP_CONTENT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linLayout = new LinearLayout(this);
linLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams linLayoutParam = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
setContentView(linLayout, linLayoutParam);
LinearLayout.LayoutParams lpView = new
LinearLayout.LayoutParams(wrapContent, wrapContent);
Button btn = new Button(this);
btn.setText("Button");
linLayout.addView(btn, lpView);
}//fin de onCreate
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn: //Here the problem begins with error 'btn'
break;
}
}
}
如何使它识别以编程方式创建的符号“ btn”对象?
谢谢。
答案 0 :(得分:0)
我不敢相信我找不到关于这个问题的问题...
如果您read the docs,Google会在页面顶部告诉您该怎么做:button.setOnClickListener()
。就您而言:
Button btn = new Button(this);
btn.setOnClickListener(this);
答案 1 :(得分:0)
就像@TheWanderer一样,您尚未指定ID
btn.setId(your_set_id);
btn.setOnClickListener(this);
然后再
switch(item.getItemId()) {
case R.id.your_set_id:
break;
}
答案 2 :(得分:0)
您可以像这样为动态创建的按钮设置ID:
Button btn = new Button(this);
btn.setText("Button");
btn.setId(4); //give a positive integer
然后获取按钮的ID,如下所示:
int buttonID = btn.getId();
和
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonID :
//do something
break;
}
}
}
已编辑:
Button btn = new Button(this);
btn.setOnClickListener(this) //add this line.
btn.setText("Button");
btn.setId(4); //give a positive integer
linLayout.addView(btn, lpView);