I have a custom view (an extension of a TextView) that I want to dynamically add to my Layout (don't want to include it in the main.xml file).
The book says to fetch the RelativeLayout using findViewById() in my java code then create a new instance of my custom view, then use addView on the RelativeLayout to add the new view.
I'm not getting any errors, but when I click my button to add the new view, nothing is happening (view isn't being added). Do I need to set additional properties on my custom view (layout width, layout height for example) in order for it to be shown?
EDIT: adding code
// changed to an imageview as I thought it might be easier to see an image
RelativeLayout rel = (RelativeLayout) findViewById(R.id.rellay);
MyCustomImageView mciv = new MyCustomImageView(null);
mciv.setId(5);
LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mciv.setLayoutParams(p);
mciv.setImageResource(R.drawable.someImage);
rel.Addview(mciv);
Please post your code where you add the view.
But yes, you might be missing the params for width and height. Try something like
LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT);
txtView.setLayoutParams(p);
or what you would like the width and height to be. Also in xml layout, layout_width and layout_height are required attributes.
Related
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);
I must be missing something really stupid.
I have a LinearLayout in my view:
_editTextViews = (LinearLayout)findViewById(R.id.editDesAndLocViews);
I am trying to dynamically change the height of that view by setting the LayoutParams
I have two LinearLayout.LayoutParams
LinearLayout.LayoutParams collapsedParams;
LinearLayout.LayoutParams openParams;
that are set in the constructor like so:
collapsedParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,0);
openParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
But as soon as i try to apply one of those params to my LinearLayout, like so:
_editTextViews.setLayoutParams(collapsedParams);
I get the following FATAL EXCEPTION:
At first i thought my project needed to be cleaned as it seems to think i am trying to force a relative layout to use linear layout params, but everything is LinearLayout. The LinearLayout in question does contain a couple RelativeLayouts. I don't know if / why that would be the problem.
please help
Change your LayoutParamss' type to either ViewGroup.LayoutParams or RelativeLayout.LayoutParams.
The LayoutParams you apply have to match the parent layout of the view. LayoutParams define how a View is layed out in its parent view (layout). Because each layout type takes different parametres for laying out a view (e.g. only LinearLayout has weight, only RelativeLayout can use anchors), they all have their own LayoutParams.
How can I retain attributes of the children in a RelativeLayout when dynamically adding ImageViews?
I have a custom ImageView I want to add at runtime to an empty RelativeLayout (nothing inside in XML), I can add the first, then move, scale and rotate them, it works fine.
When I add another ImageView all previously added instances loose their position and their size, but when I touch them they get back just their size, not the position.
In my ImageView I'm overriding onDraw and onTouch, do I need to override something else?
Maybe I have to write my own RelativeLayout implementation? I wouldn't!
This is the pseudocode for adding new ImageView:
create new instance of ImageView
set bitmap
set scaletype
add imageview to the RelativeLayout container
I even tried to set a standard layout parameter for the brand new added ImageView with the same result.
I tried to get the margins for every children, based on its position, and the re set the layout with ImgeView.setLayout(l, t, r, b);
no success...
Here's the XML RelativeLayout container, pretty simple, maybe too much?
<RelativeLayout
android:id="#+id/face_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</RelativeLayout>
Do you need more details to help me? Please ask, I can post the code too, but I have to clean it up a bit before, I can do it tomorrow, in the meantime please give me some advice.
In a RelativeLayout all view positions are related to the others views. So, as you do in xml, you should provide for each view the relative parameters.
Before add imageView to the RelativeLayout call setLayoutParams(layoutParams):
// Create a new RelativeLayout.LayoutParams instance
RelativeLayout.LayoutParams layoutParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
// add roules
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layoutParams.addRule(.........
layoutParams.addRule(.........
//add params to view
imageView.setLayoutParams(layoutParams);
//add imageview to the RelativeLayout container
yourRelativeLayout.addView(imageView);
Look here for all rules.
I have a custom view which will be jar'ed up and added into another project. In the view I want to give an option of a button.
Here is what I have in the CustomView class.
final CustomView currentView = (CustomView) findViewById(this.getId());
RelativeLayout.LayoutParams params = (new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT ));
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
closeButton.setLayoutParams(params);
currentView.addView(closeButton);
This is all wrapped in a RelativeLayout Tag as well as the other objects of the application
Everything compiles however in the CustomView the Button is aligning left instead of right.Any Ideas???
I would guess the problem is your CustomView. It probably doesn't take the entire width of the window, and is just wide enough to fill its children (which, in your case, is the close button). Make sure your CustomView has a fill_parent horizontal layout.
Since your CustomView extends WebView, which, in turn, extends AbsoluteLayout, you can't expect it to handle RelativeLayout's parameters. Instead, it's best you put your customview and your close button inside a RelativeLayout and position them properly.
When adding your closeButton to your currentView you need to supply the LayoutParams as an argument as well in order for them to take effect.
Basically, switch
currentView.addView(closeButton);
with
currentView.addView(closeButton, params);
Since the width of your button is set to wrap_content, you could also try setting its layout_gravity to right.
params.gravity = Gravity.RIGHT;
Let's say I have a LinearLayout, and I want to add a View to it, in my program from the Java code. What method is used for this? I'm not asking how it's done in XML, which I do know, but rather, how can I do something along the lines of this sample code?
(One View).add(Another View)
Like one can do in Swing.
Calling addView is the correct answer, but you need to do a little more than that to get it to work.
If you create a View via a constructor (e.g., Button myButton = new Button();), you'll need to call setLayoutParams on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.
For example, you might have the following code in your onCreate() function assuming your LinearLayout has id R.id.main:
LinearLayout myLayout = findViewById(R.id.main);
Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
myLayout.addView(myButton);
Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.
The best way I found is to use the inflate static method of View.
View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);
where yourViewXML is something like R.layout.myView
please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)
so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:
View view = getView(); // returns base view of the fragment
if (view == null)
return;
if (!(view instanceof ViewGroup))
return;
ViewGroup viewGroup = (ViewGroup) view;
View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);
EDIT:
Kotlin code for the example above (view is the getView() of a fragment)
(view as? ViewGroup)?.let {
View.inflate(context, R.layout.add_credit_card, it)
}
To add the view programmatically, you can do:
LinearLayout rlmain = new LinearLayout(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
LinearLayout ll1 = new LinearLayout (this);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.logo);
LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
iv.setLayoutParams(lp);
ll1.addView(iv);
rlmain.addView(ll1);
setContentView(rlmain, llp);
You can also add any number of views.
LinearLayout is a subclass of ViewGroup, which has a method called addView. The addView method should be what you are after.
The idea of programmatically setting constraints can be tiresome. This solution below will work for any layout whether constraint, linear, etc. Best way would be to set a placeholder i.e. a FrameLayout with proper constraints (or proper placing in other layout such as linear) at position where you would expect the programmatically created view to have.
All you need to do is inflate the view programmatically and it as a child to the FrameLayout by using addChild() method. Then during runtime your view would be inflated and placed in right position. Per Android recommendation, you should add only one childView to FrameLayout [link].
Here is what your code would look like, supposing you wish to create TextView programmatically at a particular position:
Step 1:
In your layout which would contain the view to be inflated, place a FrameLayout at the correct position and give it an id, say, "container".
Step 2
Create a layout with root element as the view you want to inflate during runtime, call the layout file as "textview.xml" :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
</TextView>
BTW, set the layout-params of your frameLayout to wrap_content always else the frame layout will become as big as the parent i.e. the activity i.e the phone screen.
android:layout_width="wrap_content"
android:layout_height="wrap_content"
If not set, because a child view of the frame, by default, goes to left-top of the frame layout, hence your view will simply fly to left top of the screen.
Step 3
In your onCreate method, do this :
FrameLayout frameLayout = findViewById(R.id.container);
TextView textView = (TextView) View.inflate(this, R.layout.textview, null);
frameLayout.addView(textView);
(Note that setting last parameter of findViewById to null and adding view by calling addView() on container view (frameLayout) is same as simply attaching the inflated view by passing true in 3rd parameter of findViewById(). For more, see this.)
One more way to add view from Activity
ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);
You guys should also make sure that when you override onLayout you HAVE to call super.onLayout with all of the properties, or the view will not be inflated!