简体   繁体   English

Java中没有XML的java中的可单击图像按钮

[英]clickable image button in java without xml in android

I want to make image button in java class without using XML(dynamic UI). 我想在不使用XML(动态UI)的java类中使图像按钮。

I can make this but I can't connect to onClick void. 我可以做到这一点,但我无法连接到onClick void。

Can anybody help me? 有谁能够帮助我?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.main);
    LayoutParams params =
            new TableRow.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);

    TableRow table = new TableRow(this);
    table.setOrientation(TableRow.VERTICAL);


    ImageButton ib = new ImageButton(this);
    ib.setImageResource(R.drawable.one);
    ib.setLayoutParams(params);
    table.addView(ib);

    TableRow.LayoutParams layoutParams=
            new TableRow.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT );
    this.addContentView(table, layoutParams);

}
public void onClick(View v){

    Toast.makeText(getBaseContext(),"This button clicked",Toast.LENGTH_SHORT).show();


}

you missed ib.setOnClickListener(...); 您错过了ib.setOnClickListener(...); . If your activity implements View.OnClickListener then it would be 如果您的活动实现了View.OnClickListener,那么它将是

ib.setOnClickListener(this);

You need to assign OnClickListener before using it 您需要先分配OnClickListener才能使用它

If you are implementing OnClickListener in the activity then use (I believe you are because you have onClick method defined) 如果您在活动中实现OnClickListener ,则使用(我相信是因为您定义了onClick方法)

ib.setOnClickListener(this);

If not then do this 如果没有,那就这样做

ib.setOnClickListener(new View.OnClickListener()
{
    public void onClick(){
        // Do as required
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM