在Android java中实现按钮的不同方式有哪些?
我知道这两个:在Android java中实现按钮的不同方式有哪些?,java,android,Java,Android,我知道这两个: 按钮b=(按钮)(findViewById(R.id.Button2)) android:onClick=“” 有什么不同的方法吗 我刚刚试过按钮b=新按钮() 但它在android中不起作用 谢谢大家! 1.Button b=(Button)(findviewbyd(R.id.Button2)) 这将为您提供用XML定义的按钮的对象 2.android:onClick=“” 此方法用于处理按钮单击事件,而不是创建按钮 3.默认构造函数不可用-new Button() 您需要在构
按钮b=(按钮)(findViewById(R.id.Button2))代码>
android:onClick=“”
按钮b=新按钮()代码>
但它在android中不起作用
谢谢大家! 1.Button b=(Button)(findviewbyd(R.id.Button2))
这将为您提供用XML定义的按钮的对象
2.android:onClick=“”
此方法用于处理按钮单击事件,而不是创建按钮
3.默认构造函数不可用-new Button()
您需要在构造函数中传递上下文
Button delete = new Button(context);
1.按钮b=(按钮)(findViewById(R.id.Button2))
这将为您提供用XML定义的按钮的对象
2.android:onClick=“”
此方法用于处理按钮单击事件,而不是创建按钮
3.默认构造函数不可用-new Button()
您需要在构造函数中传递上下文
Button delete = new Button(context);
你应使用:
编程方式:
Button b=new Button(this);
yourView.addView(b);
通过Xml(使用布局)
您应该使用:
编程方式:
Button b=new Button(this);
yourView.addView(b);
通过Xml(使用布局)
您可以通过编程方式添加按钮,请尝试以下操作:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
然后,您可以创建一个新按钮,例如,只需添加它:
Button btn = new Button(this);
btn.setText("MyButton");
btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linerLayout.addView(btn);
可以通过编程方式添加按钮,请尝试以下操作:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
然后,您可以创建一个新按钮,例如,只需添加它:
Button btn = new Button(this);
btn.setText("MyButton");
btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linerLayout.addView(btn);
试试这种方法,希望这能帮助你解决问题。
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/btnFromXml"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button From Xml"/>
<LinearLayout
android:id="@+id/lnrActivityButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
</LinearLayout>
</LinearLayout>
试试这种方法,希望这能帮助你解决问题。
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/btnFromXml"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button From Xml"/>
<LinearLayout
android:id="@+id/lnrActivityButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
</LinearLayout>
</LinearLayout>
android中有两种显示按钮的方法,一种是xml中的定义按钮,另一种是在运行时尝试添加按钮;当它在Java中工作时不工作?android中有两种显示按钮的方法,一种是在xml中定义按钮,另一种是在运行时尝试添加按钮;在Java中工作时不工作?欢迎,很乐意帮助^^欢迎,很乐意帮助^^