I have this LinearLayout in my Layout, if I copy that in my XML layout file I get another line with those three elements and everythings looks as expected. Now I try to add this LinearLayout and its child elements programmatically which works but looks differently and all wrong. The button seems to have the right width but the height is too low and the other two elements are hardly visible with wrong height and width.
This is the layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/editTextValueComposition"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.94"
android:ems="10"
android:hint="#string/valueHint"
android:inputType="numberDecimal" >
</EditText>
<Spinner
android:id="#+id/compositionSelector"
android:layout_width="176dp"
android:layout_height="wrap_content"
android:layout_weight="0.06" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addComposition"
android:text="#string/add" />
</LinearLayout>
And this is my code:
public void addComposition(View view) {
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
EditText valueEdit = new EditText(this);
valueEdit.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 0.94f));
valueEdit.setHint(R.string.valueHint);
valueEdit.setEms(10);
linearLayout.addView(valueEdit);
Spinner compositionSelector = new Spinner(this);
compositionSelector.setLayoutParams(new TableLayout.LayoutParams(dpToPx(176), LayoutParams.WRAP_CONTENT, 0.06f));
ArrayAdapter<CharSequence> adapterComp = ArrayAdapter.createFromResource(
this, R.array.compositionTypes,
android.R.layout.simple_spinner_item);
adapterComp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
compositionSelector.setAdapter(adapterComp);
linearLayout.addView(compositionSelector);
Button addCompoButton = new Button(this);
addCompoButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addCompoButton.setText(R.string.add);
addCompoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addItem(v);
}
});
linearLayout.addView(addCompoButton);
LinearLayout addItemLayout = (LinearLayout) findViewById(R.id.screenAddItem);
int index = addItemLayout.indexOfChild(findViewById(R.id.button1));
addItemLayout.addView(linearLayout, index);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getBaseContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
Try to use LinearLayout.LayoutParams instead of TableLayout.LayoutParams
Related
In my layout I have 6 spinners that are not necessaritly displayed.
When no option is selected, the height is good, but when an option is selected, it looks bigger and I didn't find anything about that online.
Here is the spinners without an option selected
And when an option is selected
Here is the Layout which contains the spinners:
<LinearLayout
android:id="#+id/layoutDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/details">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/txtDetail1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="#dimen/medium_text"/>
<Spinner
android:id="#+id/spinDetail1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#drawable/spinner"/>
</LinearLayout>
... Same thing 5 more times ...
</LinearLayout>
And here is my java code for the spinners:
private void initializeDetails() {
List<Detail> details = mainAct.details;
detailSpinners = new Spinner[details.size()];
int marginTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics());
int marginEnd = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
int marginStart = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.TOP;
for (int i = 0; i < details.size(); i++) {
int tvID = getResources().getIdentifier("txtDetail" + (i + 1), "id", mainAct.getPackageName());
int spinID = getResources().getIdentifier("spinDetail" + (i + 1), "id", mainAct.getPackageName());
TextView txtDetail = inputView.findViewById(tvID);
Spinner spinDetail = inputView.findViewById(spinID);
txtDetail.setText(details.get(i).getTitle());
List<String> answers = details.get(i).getAnswers();
answers.add("");
final int answersSize = answers.size() - 1;
ArrayAdapter<String> detailAdapter = new ArrayAdapter<String>(mainAct, R.layout.support_simple_spinner_dropdown_item, answers) {
#Override
public int getCount() {
return answersSize;
}
};
spinDetail.setAdapter(detailAdapter);
spinDetail.setSelection(answersSize);
params.setMargins(marginStart, marginTop, marginEnd, 0);
spinDetail.setLayoutParams(params);
params.setMargins(0, marginTop, marginEnd, 0);
txtDetail.setLayoutParams(params);
detailSpinners[i] = spinDetail;
}
}
I can't put a wrap_content height for the spinners because if I do they aren't visible.
I don't think that the xml is the problem because I used a lot of spinners with the same code and I never had this issue. The difference is that I edit the LayoutParams programmatically and there's probably something I'm doing wrong.
I just want the spinners to keep the same height.
Set the padding to 0 on the spinner xml element.
<Spinner
android:id="#+id/spinDetail1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:padding="0dp"
android:background="#drawable/spinner"/>
Update:
The wrapping LinearLayout has a height of "wrap_content" while the Spinner has a height of "match_parent", assuming this will act the same as wrap_content as it is only constrained by the LinearLayout.
Setting a specified height in pixels to the Spinner should resolve this.
android:layout_height="60dp"
I want XML for the TextViews and EditTexts created dynamically. Some blogs suggest that there are some Third Party Libraries that can do that but I wasn't able to find one. I am basically creating TextViews & EditTexts dynamically in my code on a button click.
Code:
LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
for (int x = 0; x < 1; x++) {
Display display = ((WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int width = display.getWidth() / 3;
TextView et1 = new TextView(this);
et1.setBackgroundColor(color.transparent);
et1.setText("Untitled");
et1.setGravity(Gravity.LEFT);
EditText et = new EditText(this);
et.setHint("Click to add");
et.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
LayoutParams lp1 = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
LayoutParams lp2 = new LayoutParams(width,
LayoutParams.WRAP_CONTENT);
// lp1.addRule(RelativeLayout.BELOW, et1.getId());
linearLayout1.addView(et1, lp2);
linearLayout1.addView(et, lp2);
XML:
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/addImage" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/addEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/scrollView1"
android:text="Edit" />
The question is, how do I achieve the XML for the TextView & EditText as a String value? Do I give them tags and ids statically in the code or is there any other way?
public static final void writeMapXml(Map val, String name, XmlSerializer out)
throws XmlPullParserException, java.io.IOException
{
if (val == null) {
out.startTag(null, "TextView");
out.endTag(null, "TextView");
return;
}
Set s = val.entrySet();
Iterator i = s.iterator();
out.startTag(null, "TextView");
if (name != null) {
out.attribute(null, "name", "TextView");
}
out.endTag(null, "TextView");
}
XMLSerializer provided by android itself is enough to make dynamic XMLs.
I have written this piece of code. But it is not giving the proper result. Please let me know where is the mistake. And I don't want to use Linear Layout.
Here is the xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/custom_relativeLayout1"
android:orientation="horizontal"
android:background="#ffffff">
</RelativeLayout>
</LinearLayout>
String[] but = {"Hello", "Bye"};
int buttonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customLayout = (RelativeLayout) findViewById(R.id.custom_relativeLayout1);
//customLayout is object of relativelayout.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (butArray[i].getId() != 1)
{
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
else
{
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
}
RelativeLayout.RIGHT_OFhoryzontally or vertically align?
so for vertically
Btnparams.addRule(RelativeLayout.BELOW, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
or for horizontally
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
instead of
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
LinearLayout is very nice to use if you want do dynamically add Views and scale them the same. For example if you want to add buttons and have max 3 buttons per row, you can also use another LinearLayout to make a new row.
I 'abuse' the LinearLayout row and a Button for layoutparams templating.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_root"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/ll_row1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"/>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2"/>
</LinearLayout>
</LinearLayout>
Example code:
// Get LL and template params
LinearLayout root = (LinearLayout) findViewById(R.id.ll_root);
LinearLayout row1 = (LinearLayout) findViewById(R.id.ll_row1);
ViewGroup.LayoutParams llRowParams = row1.getLayoutParams();
ViewGroup.LayoutParams btnParams = findViewById(R.id.btn1).getLayoutParams();
// Make new button
Button newBtn = new Button(context);
newBtn.setLayoutParams(btnParams);
newBtn.setText("Button 3");
// Add button to row1
row1.addView(newBtn);
// Add new row
LinearLayout row2 = new LinearLayout(context);
row2.setLayoutParams(llRowParams);
root.addView(row2);
// TODO: add buttons to new row
// TODO: some logic to decide between adding to row or creating new row and adding button
Note: code is not tested, but you should get the idea.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (i != 0) {
Btnparams.addRule(RelativeLayout.RIGHT_OF, i-1);
}
customLayout.addView(butArray[i], Btnparams);
}
I found online the working code of a menu slider.
In this code, however, the layout is generated in the code, could someone help me to configure it in a layout file in *. Xml?
Sorry for my bad english.
code:`
private boolean Menu_Displayed=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = getWindowManager().getDefaultDisplay();
final int width = display.getWidth();
// menu:
LinearLayout li_menu = new LinearLayout(this);
li_menu.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
li_menu.setOrientation(1);//1 is vertical
li_menu.setBackgroundColor(Color.GREEN);
Button btn1 = new Button(this);
btn1.setText("button 1");
btn1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
li_menu.addView(btn1);
//body:
final HorizontalScrollView hsv = new HorizontalScrollView(this){
#Override
// do not let hsv consume the click itself. Then the view under the hsv will also consume the click
//so that the menu will be clicked
//when menu is not showed up, let hsv be the only view to consume the click.
//so that the menu will not be clicked
public boolean onTouchEvent(MotionEvent ev) {
if(Menu_Displayed){
return false;
}
else{
return true;
}
}
};
hsv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
hsv.setBackgroundColor(Color.TRANSPARENT);
hsv.setHorizontalFadingEdgeEnabled(false);
hsv.setVerticalFadingEdgeEnabled(false);
final LinearLayout li_body = new LinearLayout(this);
li_body.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
li_body.setOrientation(0);//0 is horizantal
li_body.setBackgroundColor(Color.TRANSPARENT);
hsv.addView(li_body);
//body: place holder transparent
TextView placeholder = new TextView(this);
placeholder.setTextColor(Color.TRANSPARENT);
placeholder.setLayoutParams(new LayoutParams(width-100, LayoutParams.FILL_PARENT));
placeholder.setVisibility(View.INVISIBLE);
li_body.addView(placeholder);
//body: real content
LinearLayout li_content = new LinearLayout(this);
li_content.setLayoutParams(new LayoutParams(width, LayoutParams.FILL_PARENT));
li_content.setOrientation(1);//1 is vertical
li_content.setBackgroundColor(Color.CYAN);
TextView tv1 = new TextView(this);
tv1.setText("txt 1");
tv1.setTextSize(40);
tv1.setTextColor(Color.BLACK);
TextView tv2 = new TextView(this);
tv2.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv2.setTextSize(50);
tv2.setText("txt 2");
tv2.setTextColor(Color.WHITE);
//use this button to scroll
Button btn_showMenu = new Button(this);
btn_showMenu.setText("Menu");
btn_showMenu.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn_showMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hsv.post(new Runnable() {
#Override
public void run() {
if(Menu_Displayed){
hsv.smoothScrollTo(width-100, 0);
}
else{
hsv.smoothScrollTo(0, 0);
}
Menu_Displayed = !Menu_Displayed;
}
});
}
});
li_content.addView(tv1);
li_content.addView(tv2);
li_content.addView(btn_showMenu);
li_body.addView(li_content);
//add menu and body in to frame
FrameLayout mainFrame = new FrameLayout(this);
mainFrame.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mainFrame.addView(li_menu);
mainFrame.addView(hsv);
//scroll to the body real content to block the menu
hsv.post(new Runnable() {
#Override
public void run() {
hsv.scrollBy(width-100, 0);
}
});
setContentView(mainFrame);
}
`
This is not a good implementation of a SlidingMenu, you can try this open sources project:SideMenu
To implements the menu swap on you example, is calculating the screen width-100, width cannot be converted to xml, the base view will be like this file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff669900"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:fadingEdge="none" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<TextView
android:id="#+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingRight="100dp" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
There has been many questions on dynamically setting the position of a button, but I just want to change the position of a button into center of the screen. My layout is RelativeLayout.
Updated:
At the beginning, myButton has been set position in XML as:
<Button
android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Menu" />
Any suggestion would be greatly appreciated
See an example below (click the button and it will be moved to the center).
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/my_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Menu" />
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private View mView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mView = findViewById(R.id.my_view);
mView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewGroup.LayoutParams vg_lp = mView.getLayoutParams();
// Make sure we are in RelativeLayout
if (vg_lp instanceof RelativeLayout.LayoutParams) {
RelativeLayout.LayoutParams rl_lp = new RelativeLayout.LayoutParams(vg_lp);
rl_lp.addRule(RelativeLayout.CENTER_IN_PARENT);
mView.setLayoutParams(rl_lp);
}
}
});
}
}
Try:
......
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) button.getLayoutParams();
layoutParams.leftMargin = parentLayout.getWidth()/2;
layoutParams.topMargin = parentLayout.getHeight()/2;
button.setLayoutParams(layoutParams);
......
Try this one:
RelativeLayout RL = (RelativeLayout)findViewById(R.id.relative_layout);
RL.gravity(Gravity.CENTER);
with this all subviews of RL will be in center;
Button anyButton = new Button(this);
RL.addSubview(anyButton);//this genereted button will be in center as well
Try this,
RelativeLayout my_layout = new RelativeLayout(this);
my_layout.setId(some_value);
Button my_btn = new Button(this);
RelativeLayout.LayoutParams my_params = new RelativeLayout.LayoutParams(btn_height,btn_width);
my_params.addRule(RelativeLayout.CENTER_IN_PARENT,my_layout.getId());
my_layout.addView(my_btn,my_params);
Add this 2 lines to the component you want to center in the xml file :
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"