I'm having a problem with adding elements in code. I want to add two buttons to a horizontal linear layout. My code works, but the second button partially covers the first button.
Question: How can I make it so that the second button doesn't cover the first button?
This is the code:
public class MainActivity extends Activity {
Button buttonFirst, buttonSecond;
LinearLayout lau;
LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonFirst = new Button(getApplicationContext());
buttonSecond = new Button(getApplicationContext());
lau = (LinearLayout) findViewById(R.id.layoutmadafaka);
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(-30, 0, 0, 0);
buttonSecond.setLayoutParams(lp);
buttonSecond.setBackgroundColor(Color.BLACK);
lau.addView(buttonFirst,params);
lau.addView(buttonSecond);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<LinearLayout
android:id="#+id/layoutmadafaka"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
This must be done programmatically. When I use the bringToFront() method the buttons change positions but I don't want to do that. I want to first button on left side and second button next to first button.
I think its because of the negative margin you set :
lp.setMargins(-30, 0, 0, 0);
remove it or set them at 0 (its equivalent since 0 is the default value):
lp.setMargins(0, 0, 0, 0);
thoses negativbe margins displace the button2 to the left so its behind the other button.
You can't manage overlapping in LinearLayout (that's why a bringToFront action change order in the line and not overlapping order).
you need to use a RelativeLayout, set the button 2 to be on the right of button1, let the margin to -30 and call bringToFront on the second button it shoulc work ;)
You can set for your #id/layoutmadafaka the property android:weightSum=1.0 in xml.
And when you add the buttons, set for each layout_weight=0.5, layout_width=0.
Example here: Linear Layout and weight in Android
Related
I am trying to make buttons wrap in a LinearLayout in Android, but they are just continuing off to the right of the view (the word shown in the screenshot should be "HELLO", so I want the "O" to drop down to the next line).
I am adding the buttons programmatically, but even if I code them into the XML layout file, they still don't wrap. Here is the layout file with the LinearLayout container into which I am dynamically adding the buttons:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constrainedWidth="true"
tools:context=".LetterTileView">
<LinearLayout
android:id="#+id/TilesContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constrainedWidth="true"
android:orientation="horizontal">
</LinearLayout>
And here is the code I am using to create and add the tile buttons:
Context context = this;
LinearLayout layout = (LinearLayout) findViewById(R.id.TilesContainer);
LayoutParams params = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
params.setMargins(50, 50, 0, 0);
for (int i=0;i<wordLength;i++) {
Button tileButton = new Button(this);
tileButton.setLayoutParams(params);
tileButton.setText(wordStringtoLetters[i]);
tileButton.setId(i);
tileButton.setBackgroundResource(R.drawable.tile_button);
tileButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 36);
layout.addView(tileButton);
}
Any advice would be appreciated. Thanks!
I ended up using FlexboxLayout, which works great for this. Thanks to those who offered suggestions!
First of all, there is no need to use a ConstraintLayout you can use your LinearLayout as the parent layout.
Then for the purpose of displaying all buttons in one line, you have to set weight for the LinearLayout in XML and set weight for the views you add to it.
The xml file should look like:
<LinearLayout
android:id="#+id/TilesContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="5"
app:layout_constrainedWidth="true"
android:orientation="horizontal">
</LinearLayout>
And in code you should set weight for each view you by adding ,1.0f to LayoutParam :
Context context = this;
LinearLayout layout = (LinearLayout) findViewById(R.id.TilesContainer);
LayoutParams params = new LayoutParams( LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,1.0f );
params.setMargins(50, 50, 0, 0);
for (int i=0;i<wordLength;i++) {
Button tileButton = new Button(this);
tileButton.setLayoutParams(params);
tileButton.setText(wordStringtoLetters[i]);
tileButton.setId(i);
tileButton.setBackgroundResource(R.drawable.tile_button);
tileButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 36);
layout.addView(tileButton);
}
I want to add a text view with margins into a Relativelayout by clicking a button, but whenever I add the setMargins to the LayoutParams, it make the TextView disappeared. Here is my code
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/test11">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/test"
android:onClick="onClick"
android:text="asdf"/>
</RelativeLayout>
Here is my code:
public class tet extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
public void onClick(View v){
TextView textView = new TextView(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 30, 30, 30);
textView.setText("asdf");
textView.setLayoutParams(layoutParams);
((RelativeLayout)findViewById(R.id.test11)).addView(textView);
}
}
I'm 99% sure your TextView is behind your Button. There are several problems:
layoutParams.setMargins(30, 30, 30, 30);
This sets the margins in pixels! If you set the margins in a xml Layout they are often set as dp (you can choose the unit there). If you want dp in your code you have to convert px => dp (here you can find an example).
Secondly: You are using an RelativeLayout, hence all Views are arranged relatively in your layout. You didn't provide any infromation to you TextView so it will be placed at the left/top of its parent (so behind your Button).
Try swap your RelativeLayout for a LinearLayout or provide additional arrangement information.
For the future: These kind of problems ("my view is missing") is easily solved by the Hierarchyviewer provided by the Android SDK.
I am trying to programatically add a whole bunch of textViews of a certain width and at a certain location onto a tab. Now their setX() might be placed beyond the resolution of the screen. For instance, my tab is 1240 pixels in width, and I want to place a TextView at 2000 pixels and of course have a horizontal scroll feature available. I'm essentially creating a timeline on the fly depending on the data pulled.
I'm just trying to (at the moment) get multiple TextViews thrown on to the screen, and to have the horizontal scroll view for them. I am not sure if even doing a setX(2000); will populate a TextView beyond the screen. How can I get the HorizontalScrollView to work so that I may slide my main layout to the right to see the remaining two TextViews that were created?
Some basic code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative_layout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="horizontal">
<HorizontalScrollView
android:id="#+id/horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</HorizontalScrollView>
</RelativeLayout>
The MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
for(int i = 50; i < 550; i+=100){
TextView myText = new TextView(this);
myText.setX(i * 3);
myText.setText("HELLLLLOOOO");
layout.addView(myText);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout sv = (LinearLayout)findViewById(R.id.ll);
for(int i = 50; i < 550; i+=50){
TextView myText = new TextView(this);
myText.setX(i * 3);
myText.setText("HELLLLLOOOO");
sv.addView(myText);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
xml
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/ll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
Create one custom view for example
public class Example extends HorizontalScrollView {
}
Execute all unimplemented methods, then write this:
LinearLayout l = new LinearLayout(context);
TextView tv = new TextView(context);
tv.setText("Example");
tv.setTextColor(Color.RED);
l.addView(tv);
addView(l);
Now in your xml, put the packagename and class name like this:
<com.argha.Example android:height and all />
Done, now you have HorizontalScroll view with a TextView... more text you want just do same as above.
Sorry if you found any code error, because I typed with my phone.
I am having a LinearLayout whose visibility is directly affected by the click of a TextView. This LinearLayout has more TextViews dynamically added inside. My LinearLayout viewQuickLinks starts out with a visibility of gone. In my oncreate I call addQuickLinks which then adds several TextViews to the LinearLayout. None of these TextViews have a set visibility. I click on the TextView to change the LinearLayout to visible and space is added, but there are no TextViews.
My xml file (just to add a note this is all in a scrollview):
<TextView
android:id="#+id/textQuickLinksTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="#drawable/navigation_expand"
android:text="#string/quick_links_title"
android:textSize="25sp"
android:visibility="visible" />
<LinearLayout
android:id="#+id/viewQuickLinks"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:visibility="gone"
android:orientation="vertical" />
Changing the LinearLayout to visible and gone:
private void setUpQuickLinks() {
final TextView quickLinksTitleText = (TextView) findViewById(R.id.textQuickLinksTitle);
quickLinksTitleText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout viewQuickLinks = (LinearLayout) findViewById(R.id.viewQuickLinks);
if (viewQuickLinks.getVisibility() == View.VISIBLE){
viewQuickLinks.setVisibility(View.GONE);
quickLinksTitleText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.navigation_expand, 0);
}
else{
viewQuickLinks.setVisibility(View.VISIBLE);
quickLinksTitleText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.navigation_collapse, 0);
}
}
});
quickLinksClickListeners();
}
Why are the TextViews not appearing when the LinearLayout is Visible?
Thank you for any help!
Try changing android:layout_height to fill_parent. Why is it 1 dip?
I have to split a Single Linear layout into a Two Columns(Like newspaper Columns).The linear layout contain text-view and image-view
I have taken the screen width and have divided it to half and made the TextView and ImageView to come in a first column , ie, A B C blocks in the picture below.. now the remaining TextView and 'ImageView has to go to next column like in D E F like that it goes on.So it would be helpful if anyone gives me any code or ideas to implement this.. I tried with GridView which is not suitable for my issue. Since the TextView and ImageView sizes are not definite.
I don't know how to split Liner layout.
I tried with calculating the rootlayout height
like this
linearLayout.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
int linsize=linearLayout.getHeight();
int relsize=root.getHeight();
int textsize=txt1.getHeight();
mainheight=relsize;
subheight=linsize;
Toast.makeText(getApplicationContext(), "Linerlayout "+linsize, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Relative layout"+relsize, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "text height "+textsize, Toast.LENGTH_LONG).show();
if(mainheight==subheight)
{
Toast.makeText(getApplicationContext(), "make a new linear layout", Toast.LENGTH_LONG).show();
createsubview();
}
}
});
Screenshot
You could easily do this with nested LinearLayouts:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/item" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
content here/>
<TextView
content here/>
</LinearLayout>
</LinearLayout>
Then all that you need to do is put A, B and C in the first vertical layout, and D, E and F in the second.
You can't do it with GridView. You would have to create a custom view to do this.
if you know how big your grid items are, you can cut some corners. GridView is complicated mostly because it deals with items of any size and loads them dynamically. An easier way for you might be:
1.Create a HorizontalScrollView with a horizontal LinearLayout inside.
2.Determining how many rows of your item will fit on the screen. Call this rows.
3.while you still have items you need to layout:
1.Create a vertical LinearLayout, adding rows or less items to it.
2.Add your new vertical LinearLayout to the horizontal one.
There are some downsides versus what a "horizontal GridView" would get you:
1.All the views are loaded up immediately, which is bad for huge lists of items.
2.You need to know how big your items are, and they need to be the same size.
Upsides:
1.It's very easy to implement.
for more inf plz see this link
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView scrollView = new ScrollView(this);//ScrollView
LinearLayout ll = new LinearLayout(this); //root LinearLayout
ll.setOrientation(LinearLayout.HORIZONTAL);//with horizontal orientation
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,1f);
LinearLayout l2 = new LinearLayout(this); //sub linearlayout
l2.setOrientation(LinearLayout.VERTICAL);//with vertical orientation
l2.setLayoutParams(layoutParams);
LinearLayout l3 = new LinearLayout(this); //sub linearlayout
l3.setOrientation(LinearLayout.VERTICAL);//with vertical orientation
l3.setLayoutParams(layoutParams);
int totalvalues=41; //i take count as 41
for(int i=0;i<totalvalues;i++){ // add the buttons in the layout based on condition
Button okButton=new Button(this);
okButton.setText("Button"+i);
if(i<=totalvalues/2){
l2.addView(okButton);
}
else{
l3.addView(okButton);
}
}
ll.addView(l2); //add sub linearlayout to root linearlayout
ll.addView(l3); //add sub linearlayout to root linearlayout
scrollView.addView(ll); //add the root linearlayout to scrollview
setContentView(scrollView);
}
Have you tried:
DisplayMetrics metrics = getResources().getDisplayMetrics();
float dpW = 0f;
int pixelsW = (int) (metrics.density * dpW + 0.5f);
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(pixelsW, LayoutParams.WRAP_CONTENT, 1f);
TextView txt = new TextView(MainActivity.this);
ImageView img = new ImageView(MainActivity.this);
txt.setLayoutParams(lp);
img.setLayoutParams(lp);
Using TableLayout's LayoutParams, you can set the weight of the view, which, as you know, must be 1. We also use DisplayMetrics to convert a float into the "dp" format used in xml.
EDIT:
You can also set this LayoutParams to a LinearLayout.