I'm trying to build an android application that features a graphical display drawn within a RelativeLayout. I want to place "+" and "-" buttons next to several of the parameters, which are drawn at various points on the canvas. The positions are free-form don't seem to conform to any of the standard XML layouts.
I know how to create the buttons programmatically, but I don't know how to place them over the canvas where I need them to be. I'm assuming that this would be done in the view thread's doDraw() method, after all the graphics have been drawn, but how?
I struggled with the same problem, and found out great solution.
RelativeLayout rules like "leftOf" or "rightOf" can be implemented programmatically like this:
RelativeLayout container = new RelativeLayout(getApplicationContext());
Button weight = new Button(getApplicationContext());
final int WEIGHT_ID = 0;
weight.setId(WEIGHT_ID);
weight.setText("0.0");
LayoutParams wrapBoth =
new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
container.addView(weight, wrapBoth);
Button increaseWeight = new Button(getApplicationContext());
increaseWeight.setText("+");
// Note the difference: RelativeLayout.LayoutParams in spite of LayoutParams
RelativeLayout.LayoutParams toBeRightOfWeight =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
container.addView(parameter,wrapBoth);
// Sweet part
clearAirParams.addRule(RelativeLayout.RIGHT_OF, WEIGHT_ID);
container.addView(increaseWeight, toBeRightOfWeight);
So, in code you can create a 'container' RelativeLayout, then add several Views with unique ID's and, finally, create RelativeLayout.LayoutParams object to achieve sweet-like-sugar methods for alignment, like in XML.
Related
I have an Open GL ES 2.0 app and am displaying an Android TextView over the top of my GLSurfaceView.
I have the actual textviews displaying OK but now I need to try to centre them.
This is what I have so far:
text1 = new TextView(this);
text1.setText("This is some sample text");
text1.setTextColor(Color.WHITE);
text1.setTextSize(textSize);
text2= new TextView(this);
text2.setText("And this is some more sample text");
text2.setTextColor(Color.WHITE);
text2.setTextSize(textSize);
RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT);
lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
textLayout = new RelativeLayout(this);
textLayout.setLayoutParams(textParams);
textLayout.addView(text1);
textLayout.addView(text2);
mainLayout.addView(textLayout);
However, when I run this, only text1 is centered. Text 2 isn't, and starts at the left side of the first (correctly centered) textView. Try as I might, I can't seem to get both of them centered. The following graphic describes what I mean:
(Please note re vertical placement - in my actual results, both TextViews are at the same vertical/'y' position and therefore overlapping - obviously this is expected as I haven't changed the vertical position of the 2nd TextView, but to make things clearer to illustrate, I've moved the 2nd one down manually.......)
The idea I was going with was creating a 'textLayout' to which I could add all of my textViews, then just add that textLayout to my main layout. Thus facilitating the addition and removal of all of the textViews with a single line of code.
Please note that I am not using, and do not wish to use, XML for this - I would like to know how to do this programmatically.
What am I missing?
Edit Here is how I am creating my Main Layout to which I am adding the textView.....
layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
When you are adding "RelativeLayout.CENTER_HORIZONTAL" as a rule to your layout params, what you are actually doing is telling textLayout that it should be centered horizontally in your mainLayout (see http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#attr_android:layout_centerHorizontal). In code you should actually do text1.setGravity(Gravity.CENTER) and text2.setGravity(Gravity.CENTER).
In general, I'm trying to understand if it's possible in Android to arbitrarily change the properties of a view programmatically.
I understand that there are many properties that can be changed via methods (e.g. TextView.setBackgroundColor() among many others) but there aren't methods for every possible property.
Specifically, I'm interested in instantiating a custom View and then changing the layout_weight. I'm interested in learning how to do this, but in general I want to know how I'm supposed to create a custom View if I can't change it's properties programmatically. I understand I can change all its properties in xml (including custom xml properties) but I want to be able to instantiate the view at run-time.
layout_ attributes are actually slightly different than most other things as explained in this pro-tip: they're instructions to the parent ViewGroup and are stored in their LayoutParams.
For example, layout_weight in a LinearLayout would be found in LinearLayout.LayoutParams. This means you can change them by doing
LinearLayout.LayoutParams params =
(LinearLayout.LayoutParams) yourCustomView.getLayoutParams();
// Set the weight however you like
params.weight = 4.0f;
Creating the view allows you to do this as well:
LinearLayout parentLayout = ...;
YourCustomView yourCustomView = ...;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, // width
LayoutParams.WRAP_CONTENT, // height
1.0f); // weight
parentLayout.addView(yourCustomView, params);
Right, this is a strange problem I have been toying with for a while now, hopefully maybe I am missing something you guys can draw my attention to!
LinearLayouts seem to be disappearing once I add any spacing using views and defining the weight (a method which works elsewhere in the project).
I have a custom Dialog (extends Dialog). In the onCreate() I use the method setContentView(generateDialog()) which returns a vertical LinearLayout.
The LinearLayout has three elements, one row of four custom category buttons (LinearLayouts), one row of sorting buttons (also LinearLayouts) and one ListView which populates the rest of the dialog and refreshes based on which button is pressed.
All is functional and working fine. Except when I attempt to space the buttons out evenly using my spacer method:
Dialog.java:
LinearLayout catBtns = new LinearLayout(context);
catBtns.setOrientation(LinearLayout.HORIZONTAL);
catBtns.setBackgroundResource(R.drawable.btn_cat_gradient_bg);
catBtns.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
catBtns.addView(space(1));
cat1Btn = new CatButton(context,this,act,"CAT1");
catBtns.addView(cat1Btn);
catBtns.addView(space(1));
cat2Btn = new CatButton(context,this,act,"CAT2");
catBtns.addView(cat2Btn);
catBtns.addView(space(1));
cat3Btn= new CatButton(context,this,act,"CAT3");
catBtns.addView(cat3Btn);
catBtns.addView(space(1));
cat4Btn = new CatButton(context,this,act,"CAT4");
catBtns.addView(cat4Btn);
catBtns.addView(space(1));
The space() method:
private View space(int space) {
View view = new View(context);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0,0);
p.weight = space;
view.setLayoutParams(p);
return view;
}
What confuses me is that I have been using this method throughout the project and can't find as to why the category LinearLayout DISAPPEARS COMPLETELY when I add the spacers in between each button.
I use the same technique for the sorting buttons and it works perfectly! I use the same technique in another part of the project using slightly different versions of the same buttons (they are different class files though, because the onClickListener and some other stuff is slightly different)
Anyone have any clue?
I tried to build this in XML and it works fine. A possible difference is, that you do not set any LayoutParams for your buttons. Try something like that for every button:
cat1Btn = new CatButton(context,this,act,"CAT1");
catBtns.addView(cat1Btn, new LinearLayout.LayoutParams(0,0));
There are plenty of similar questions asked in SO, but then also, please take time to read my question.
I need to create a UI programmatically that would have multiple ImageView, all positioned at different location of the screen and having their associated click events (its a game app). I found that FrameLayout is appropriate choice, where I can set margins on my own and have it positioned at desired location.
Now, I'm confused whether to have FrameLayout for every single ImageView I create, or to keep single FrameLayout and add all ImageViews within it, but set each imageview at different position.
In either of the case, how can I add FrameLayout, and ImageView within it, programmatically and also set its margin such that it can be placed anywhere on the screen.
Note that my main canvas, which will carry all these ImageViews has background, and the canvas is a LinearLayout set via XML, so my onCreate() already has setContentView(R.layout.game_canvas);, and I'd be using addContentView() to add additional views, but this method too accepts LayoutParams object as it second parameter, so what exactly should I set for this, when I add my FrameLayouts using this method?
My question might be confusing itself, so please let me know if I need to elaborate.
FrameLayouts are designed to only hold one View, so this isn't really the appropriate choice.
Use a RelativeLayout to hold all of your ImageViews. You can position each ImageView by setting the margins in their LayoutParams.
E.g. The following code would place an ImageView at coordinates 50,50:
RelativeLayout imgLayout = new RelativeLayout(this);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.an_image);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(50, 50, 0, 0);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
imgLayout.addView(iv, lp);
You can then add this RelativeLayout to your main LinearLayout using its addView() method.
I have a relativeLayout like below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/parent" >
<ListView
android:layout_width="360dp"
android:layout_height="600dp"
android:id="#+id/list"
android:inputType="text"
android:maxLines="1"
android:layout_margin="50dp"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
In the java code, I want to add a view to the left of the listview, but it didn't worked:
m_relativeLayout = (RelativeLayout)findViewById(R.id.parent);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.LEFT_OF, m_listView.getId());
Button button2 = new Button(this);
button2.setText("I am button 2");
m_relativeLayout.addView(button2, layoutParams);
only if I set the listview to alignParentRight, it will work. Is this an android bug or I'm missing something?
I always try addView(View child, int index, LayoutParams params), but it might only work in the linearlayout. So is there an normal solution to make the RelativeLayout.LEFT_OF work?
EDIT
I have tried RelativeLayout.BELOW and RelativeLayout.RIGHT_OF, and they worked perfectly, so it means I don't have enough place to get the button? I tried to give more space, but it still not work.
I use Toshiba AT100 (1280*800) and landscape, so the space is enough. Test below and right just same as the left. I think If i put an control A in the relativelayout, then I add control B and decalare it's on the left of the control A, the result should be the control B will push the control A to its right, right?
I think If i put an control A in the relativelayout, then i add control B and declare it's on the left of the control A, the result should be the control B will push the control A to its right, right?
Your assumption is incorrect, the control A will not be pushed to the right unless you specified this with a RelativeLayout.LayoutParams rule. RelativeLayout places its children one one top of each other starting at the top-left corner of the screen if you don't specify placement rules for them. When you add the View A to the RelativeLayout without any rules(like layout_alignParentRight) it will be placed starting from the top-left corner of the screen. Then, when you add the View B, the rule to_leftOf will apply to this View position but this rule doesn't mean anything for the View A who will maintain its position on the screen. This will make View B to be place to the left of View A but outside of the screen as View A bounds start from the left border of the screen.
The Button will be placed to the left of the ListView when you use layout_alignParentRight="true" because there is now space to actually see the Button(it's not outside anymore). addView(View child, int index, LayoutParams params) works in a LinearLayout because the LinearLayout arranges its children in a row or column(depending on orientation) so when you add a View at a specific position, it will push the other Views after it to the right or below(depending on orientation)(there is no relative positioning of the views in a LinearLayout, the only rule is that the children come one after the other).
Starting with the ListView without any rules set on it, here is an example on how to make the Button to appear on the left of the ListView:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
Button button2 = new Button(this);
button2.setText("I am button 2");
button2.setId(1000);
m_relativeLayout.addView(button2, layoutParams);
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) m_listView
.getLayoutParams();
rlp.addRule(RelativeLayout.RIGHT_OF, button2.getId());
The Button will be added as normal to the screen and it will appear starting from the top-left corner of the screen. Without the two lines from the code above the Button and ListView will overlap as this is the normal behavior of RelativeLayout for children without any rules on them. We then explicitly modify the position of the ListView to move it to the right(with the last two line from the code above).
If your variable names are indicative, it's because you are adding the widget to a LinearLayout, so tags for a RelativeLayout get ignored.
This line is the one I'm talking about:
m_linearLayout.addView(button2, layoutParams);
EDIT
You say alignParentRight works... the only difference there is that ot doesn't take an anchor parameter. Perhaps m_listView.getId() isn't returning the proper id. You could step through with the debugger and see if it's returning a proper value.
Maybe you could try calling the id specifically...
layoutParams.addRule(RelativeLayout.LEFT_OF, R.id.list);
To perform it, use predefined view ID or declare one. In values folder create ids.xml then add a Item like this:
<item name="imageViewID" type="id"/>
use this id in your code where you are creating new Instance of view like this:
RelativeLayout layout=new RelativeLayout(context);
ImageView imageView = new ImageView(context);
imageView.setId(R.id.imageViewID);
RelativeLayout.LayoutParams layoutParams = new LayoutParams(50, 50);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layout.addView(imageView, layoutParams);
TextView textView = new TextView(context);
RelativeLayout.LayoutParams textViewParams= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
textViewParams.addRule(RelativeLayout.BELOW, imageView.getId());
layout.addView(nameView, nameLayoutParams);
or we can directly use this function View.generateViewId() to perform the same. Like this:
imageView.setId(View.generateViewId());
I think you might have forgotten to add m_listView to the RelativeLayout or m_listView's visibility would be GONE.
Can you please check for that?
setId before align is called, especially for the new object view.
If you are using a custom id and not a regular generated Android id (eg. R.id.my_id), make sure that the id is not equal to 0 (or negative), otherwise the rule will be ignored.