Programmatically Center LinearLayout within another LinearLayout - java

I need to place two TextViews side by side inside a centered view.
I tried asking a similar question yesterday, only with relative layouts. I've made a lot of progress since switching to linear layout for the parent of the two TextViews, so I'd like to see if anyone can add the final component.
Here's what I have:
public void addTableLink(String s, String s1, int g, LinearLayout L, int fsize, int textColor, int backgroundColor, int lpad, int tpad, final String section, final String selection){
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setGravity(Gravity.CENTER_VERTICAL);
ll.setLayoutParams(new LinearLayout.LayoutParams(400, 30, Gravity.CENTER_HORIZONTAL));
ll.setBackgroundColor(backgroundColor);
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
tv1.setText(s);
tv2.setText(s1);
tv1.setTextSize(fsize);
tv2.setTextSize(fsize);
tv1.setTextColor(textColor);
tv1.setTextColor(textColor);
ll.addView(tv1);
ll.addView(tv2);
L.addView(ll);
}
Which gives me this:
All I need now is to get that "Company: Google" section (the white part) to be centered above, while keeping the text left aligned.
Any suggestions?

Solved it. Here's the code, all you need to do is center the view that is passed to this method (LinearLayout L) and it works great (the secret is setting the new view to horizontal):
public void addTableLink(String s, String s1, int g, LinearLayout L, int fsize, int textColor, int backgroundColor, int lpad, int tpad, final String section, final String selection){
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setGravity(Gravity.CENTER_VERTICAL);
ll.setLayoutParams(new LinearLayout.LayoutParams(400, 30));
ll.setBackgroundColor(backgroundColor);
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
tv1.setText(s);
tv2.setText(s1);
tv1.setPadding(lpad, tpad, 0, 0);
tv1.setTextSize(fsize);
tv2.setTextSize(fsize);
tv1.setTextColor(textColor);
tv2.setTextColor(Color.BLUE);
tv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setMainView(section, selection);
setTitle(section);
}
});
ll.addView(tv1);
ll.addView(tv2);
L.addView(ll);
}

Related

How get a component by programmely added id in Java for Android

I have a problem with ids on Java for Android.
I do some TextView by code, and give it an id. But I can't get the TextView with the id I gave it.
I tried to do this, but it's wont work.
LinearLayout ll;
int id = 2000000;
private void init() {
ll = findViewById(R.id.layout);
}
private TextView addTV(int x, int y, int width, int height) {
TextView tv = new TextView(this);
tv.setId(id);
id++;
tv.setText("Hello");
return tv;
}
private void changeTextTV(int id, String text) {
TextView tv = findViewById(id); //<- this is wrong, but I don't know what is right
tv.setText(text);
}
init();
ll.addView(addTV(0,0,100,100));
changeTextTV(2000000, "It's me");
Could you help me ?
PS : I'm French, so sorry for my spelling mistakes
The documentation for findViewById says that it:
Finds the first descendant view with the given ID, the view itself if the ID matches getId(), or null if the ID is invalid (< 0) or there is no matching view in the hierarchy.
with emphasis added to "descendant view." I think the issue is that you're creating a TextView but you're leaving them dangling - they're not added to the LinearLayout and then, because they're not added to the hierarchy, you fail to find them when you look for them. Consider the following:
private TextView addTV(int x, int y, int width, int height) {
TextView tv = new TextView(this);
tv.setId(id);
id++;
tv.setText("Hello");
ll.addView(tv); // <--- This is the change
return tv;
}
This is a reference to the answer found here.
after long time search and do more test. I find some answer, you have 2 choise to get the component by a setted ID :
if you want by a hard ID :
#SuppressLint("ResourceType")
private void changeTextTV(String text) {
TextView tv = findViewById(2000000);
tv.setText(text);
}
or by a variable
private void changeTextTV(int id, String text) {
TextView tv = findViewById(id);
tv.setText(text);
}
Thanks for the time you spend for me.

How to center text vertically in a TextView with Java code?

I know this question has been asked many times on SO. I have read most of them, but they don't work for me, so don't bother marking duplicates.
Here is my code, and what I have tried so far:
RelativeLayout container = new RelativeLayout(this.getContext());
TextView tv = new TextView(this.getContext());
tv.setText(txt); // a single digit like '3'
tv.setLines(1);
tv.layout(0, offsety, cellszie, offsety+cellsize);
tv.setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
tv.setGravity(Gravity.CENTER);
// I also tried CENTER_VERTIAL and the following line
// tv.setGravity(CENTER_VERTIAL| CENTER_HORIZONTAL);
// I also tried giving LayoutParams to tv like this:
// tv.setLayoutParams(new LayoutParams(cellsize, cellsize));
// tv.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
// tv.setLayoutParams(new LayoutParams(MATCH_PARENT, MATCH_PARENT));
container.addView(tv);
The character is horizontally centered, but it floats on the top of the TextView vertically. Setting gravity and LayoutParams doesn't change its behavior.
What should I do to make it center vertically?
use this class for VerticalTextView.
public class VerticalTextView extends TextView {
final boolean topDown;
public VerticalTextView(Context context, AttributeSet attrs){
super(context, attrs);
final int gravity = getGravity();
if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
topDown = false;
}else
topDown = true;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
#Override
protected void onDraw(Canvas canvas){
TextPaint textPaint = getPaint();
textPaint.setColor(getCurrentTextColor());
textPaint.drawableState = getDrawableState();
canvas.save();
if(topDown){
canvas.translate(getWidth(), 0);
canvas.rotate(90);
}else {
canvas.translate(0, getHeight());
canvas.rotate(-90);
}
canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());
getLayout().draw(canvas);
canvas.restore();
}
}
you can do it like this
RelativeLayout container = new RelativeLayout(this.getContext());
View view = layoutInflater.inflate(R.layout.my_layout_file, null);
container.addView(view);
where R.layout.my_layout_file contains textview with gravity center. and here you can get object of textview like this
textviewObject = (TextView)view.findViewById(R.id.textViewId)
Try setting RelativeLayout.LayoutParams to you RelativeLayout
RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
container.setLayoutParams(relativeLayoutParams)
Then set the gravity for your TextView:
tv.setGravity(Gravity.CENTER);
Then add the view to your RelativeLayout:
container.addView(tv);

How do I get buttons not to sit on top of each other in RelativeLayout

I'm having a problem with this code. I need to dynamically add buttons to my layout. This code works fine, with one exception. The second button sits on top of the first. This must have something to do with LayoutParams, but I'm not sure what.
private void buttonmaker (Button button)
{
RelativeLayout.LayoutParams rlayout = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rlayout.addRule(RelativeLayout.CENTER_VERTICAL);
rlayout.addRule(RelativeLayout.ALIGN_LEFT);
rlayout.width = 100;
button.setId(Atom.count);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
atoms[id].getname();
TextView textview = (TextView)findViewById(R.id.textView2);
textview.setText(textview.getText()+String.valueOf(atoms[id].getname()));
}
});
if (Atom.count > 1) rlayout.addRule(RelativeLayout.RIGHT_OF,Atom.count-1); else rlayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
button.setLayoutParams(rlayout);
RelativeLayout v = (RelativeLayout) findViewById(R.id.rlayout);
v.addView(button);
}
the problem is you set de button in the relativelayout, in this component the objects are being added one above the other, you try create linearlayout global with orientation vertical or horizontal depending on what you want and added buttons, and its all

Scroll TextView to text position

I want to scroll my TextView to make visible a specific position in the text. How can I do that? I tried bringPointIntoView (int offset) but without success.
Source code:
public class TextScrollActivity extends Activity {
public void onCreate (final Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
final int position = 500;
final TextView textView = new TextView (this);
final ScrollView scrollView = new ScrollView (this);
scrollView.addView (textView);
Button button = new Button (this);
button.setText ("Scroll to " + position);
LinearLayout layout = new LinearLayout (this);
layout.setOrientation (LinearLayout.VERTICAL);
layout.addView (scrollView,
new LayoutParams (LayoutParams.FILL_PARENT, 200));
layout.addView (button, new LayoutParams (LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
StringBuilder builder = new StringBuilder ();
for (int i = 0; i < 1000; i++)
builder.append (String.format ("[ %05d ] ", i));
textView.setText (builder);
setContentView (layout);
button.setOnClickListener (new OnClickListener () {
public void onClick (View v) {
System.out.println (textView.bringPointIntoView (position * 10));
// scrollView.scrollTo (0, position * 10); // no
}
});
}
}
For those who have the same problem, I finally made my own implementation of bringPointIntoView:
public static void bringPointIntoView (TextView textView,
ScrollView scrollView, int offset)
{
int line = textView.getLayout ().getLineForOffset (offset);
int y = (int) ((line + 0.5) * textView.getLineHeight ());
scrollView.smoothScrollTo (0, y - scrollView.getHeight () / 2);
}
Don't hesitate if you have a better solution.
Does adding a movement method to the text view solve the problem?
textView.setMovementMethod(new ScrollingMovementMethod());
Just FYI for anyone else with the same problem, on a listView with large listItems, the overloaded bringPointIntoView can be passed a ListView instead of a ScrollView and use the ScrollTo method instead of smoothScrollTo.

Create a new TextView programmatically then display it below another TextView

String[] textArray={"one","two","asdasasdf asdf dsdaa"};
int length=textArray.length;
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int i=0;i<length;i++){
TextView tv=new TextView(getApplicationContext());
tv.setText(textArray[i]);
relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
layout.addView(tv, relativeParams);
}
I need to do something like that.. so it would display as
one
two
asdfasdfsomething
on the screen..
If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.
Complete code:
String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for( int i = 0; i < textArray.length; i++ )
{
TextView textView = new TextView(this);
textView.setText(textArray[i]);
linearLayout.addView(textView);
}
Try this code:
final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];
for (int i=0; i<str.length; i++)
{
tv[i] = new TextView(this);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params.leftMargin = 50;
params.topMargin = i*50;
tv[i].setText(str[i]);
tv[i].setTextSize((float) 20);
tv[i].setPadding(20, 50, 20, 50);
tv[i].setLayoutParams(params);
rl.addView(tv[i]);
}
public View recentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a relative layout and add a button
relativeLayout = new RelativeLayout(this);
btn = new Button(this);
btn.setId((int)System.currentTimeMillis());
recentView = btn;
btn.setText("Click me");
relativeLayout.addView(btn);
setContentView(relativeLayout);
btn.setOnClickListener(new View.OnClickListener() {
#Overr ide
public void onClick(View view) {
//Create a textView, set a random ID and position it below the most recently added view
textView = new TextView(ActivityName.this);
textView.setId((int)System.currentTimeMillis());
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
textView.setText("Time: "+System.currentTimeMillis());
relativeLayout.addView(textView, layoutParams);
recentView = textView;
}
});
}
This can be modified to display each element of a String array in different TextViews.
You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).
You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

Categories

Resources