Android Button Programmaticallly
I have following structure in XML.
<LinearLayout android:id="@+id/tagsTable"
android:layout_width="fill_parent" and开发者_C百科roid:layout_height="wrap_content"
android:layout_margin="10dip" android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="Tag" android:layout_margin="2px"></Button>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/btn_white_add_9"
android:text="This Tag is very big that it has full width :)" android:layout_margin="2px"
android:paddingLeft="5px" android:paddingRight="25px"></Button>
</LinearLayout>
</LinearLayout>
Above layout results into...
But when the same thing I do with that code.
LinearLayout tagsTable = (LinearLayout) findViewById(R.id.tagsTable);
tagsTable.removeAllViews();
LinearLayout currentRow = new LinearLayout(this);
MarginLayoutParams params = new MarginLayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setTag(Id);
button.setText(Name);
button.setTextColor(0xFF736F6E);
button.setPadding(10, 0, 30, 0);
button.setOnTouchListener(new TagTouchListener());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(2, 2, 2, 2);
button.setLayoutParams(params);
button.setBackgroundResource(R.drawable.btn_blue_add_9);
currentRow.addView(button);
tagsTable.addView(currentRow);
The prominent problems are of vertical spacing and size of the button which is changed in both scenarios. The XML way is doing it perfect. What I am doing wrong in code?
In xml you have :
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
So in java you could try :
currentRow.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
精彩评论