android - addView to layout with java -
i trying understand how add views programatically (with java) in android applications. created simple layout (below) practice struggle solve following error:
java.lang.illegalstateexception: not find method addingview() in parent or ancestor context android:onclick attribute defined on view class android.support.v7.widget.appcompatbutton id 'button'
my xml:
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:id="@+id/activity_main" 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="com.example.android.view_create_test_1.mainactivity"> <linearlayout android:id="@+id/top" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="4" android:background="#555555"> </linearlayout> <relativelayout android:id="@+id/bottom" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#116677"> <button android:text="add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button" android:layout_centerinparent="true" android:onclick="addingview"/> </relativelayout> </linearlayout>
my java:
public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } public void addingview (){ linearlayout top = (linearlayout) findviewbyid(r.id.top); linearlayout newlayout = new linearlayout (this); linearlayout.layoutparams params = new linearlayout.layoutparams(viewgroup.layoutparams.match_parent, viewgroup.layoutparams.wrap_content); newlayout.setlayoutparams(new actionbar.layoutparams(actionbar.layoutparams.wrap_content, 50)); top.addview(newlayout,params); } }
please me out how solve error. thanks
your method should come this
public void addingview (view view){ linearlayout top = (linearlayout) findviewbyid(r.id.top); linearlayout newlayout = new linearlayout (this); linearlayout.layoutparams params = new linearlayout.layoutparams(viewgroup.layoutparams.match_parent, viewgroup.layoutparams.wrap_content); newlayout.setlayoutparams(new actionbar.layoutparams(actionbar.layoutparams.wrap_content, 50)); top.addview(newlayout,params); }
Comments
Post a Comment