Click here to Skip to main content
15,894,106 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
hi everyone . i want to create a Button in my android app

this is my code :
Button B=new Button(this);
B.setText="do!";

when i run my app i cant see any Button in my device!
Posted
Comments
[no name] 20-Sep-13 10:13am    
What are you adding the button to?
Richard C Bishop 20-Sep-13 10:14am    
Indeed, you are not adding the button to anything.
Sergey Alexandrovich Kryukov 20-Sep-13 10:19am    
Do the comments above close the issue?
It's apparent that just calling a constructor does not change the UI. Now grab the API documentation and see how add one control to its parent...
—SA

You need to do something like:
Java
Button myButton = new Button(this);
myButton.setText("Click Me!");

LinearLayout ln = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ln.addView(myButton, lp);
 
Share this answer
 
Comments
seyed mahmud shahrokni 21-Sep-13 9:02am    
hi , i have 2 problems whit your code

i dont have any buttonlayout in my xml codes , and i dont know what is my default LinearLayout name .
what is LayoutParams , when i wrote it , it was rejected by compiler ! should i import anything to my code ??
ridoy 21-Sep-13 9:51am    
So you need to look at this tutorial:http://thedeveloperworldisyours.com/android/add-a-textview-and-a-button-to-linear-layout-programmatically/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900