I have a LinearLayout
View with a OnClick
handler and I want to add a View after the LinearLayout programatically when the OnClick event is fired.
public void onClick(View view) {
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout info = (LinearLayout) li.inflate(R.layout.infolayer, null);
// view.addViewAfter(info)
}
info
is the View i want to add. view
is the View on which the click goes and after which I开发者_开发知识库 want to add info
.
How can I do that?
IF u want add a view after the current linear layout then first get the id of the parent layout in which the linear layout is .
for example let u have the the Linear Layout with id "ll" in relative layout(having id parentlayout) and on a button click u want add the text view under the liner layout
public void onClick(View view) {
RelativeLayout rl=new RelativeLayout(this);
TextView tv=new TextView(this)
//set param value ur requirement
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW,R.id.ll);
}
Assuming you have a known amount of linearlayouts could you just place them inside the XML resource and mark them as 'GONE'. When the event occurs make them visible. When they are marked as gone they shouldnt be taking any screen space up.
You can insert through coding and you don't need to inflate. You can create a view of any type calling the constructor and passing the context. A reference to the context can be stored on the view as a field, when the view is being constructed. This way you can always create your view on the fly.
To add the view to the LinearLayout
, you just need to call addView
. And afterwards, if you would want to remove it, just call removeView
.
But the onClick
event is inside the LinearLayout
object? This might be a problem because the views inside the the LinearLayout
might consume the event before it reaches your method. See this post to learn about that.
精彩评论