android - How to code Relative layout in java, instead of xml? -


i want run app using java code instead of xml files.
app not working on phone/emulator , crashing every time.

the code looks this:

package com.nikhil.relativelayoutjavacode;  import android.support.v7.app.actionbaractivity;     import android.os.bundle;     import android.view.menu;      import android.view.menuitem;      import android.widget.button;      import android.widget.edittext;      import android.widget.relativelayout;        import android.widget.relativelayout.layoutparams;        import android.widget.textview;        public class mainactivity extends actionbaractivity {      relativelayout main;     edittext usernamevalue, passwordvalue;     textview message, username, password;     layoutparams messagedimensions;     button login;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          init();         createmessagetextview();         main.addview(message, messagedimensions);         setcontentview(main);     }      private void init() {         // todo auto-generated method stub         main = new relativelayout(this);         layoutparams maindimensions = new layoutparams(                 layoutparams.match_parent, layoutparams.match_parent);         main.setlayoutparams(maindimensions);          usernamevalue = new edittext(this);         passwordvalue = new edittext(this);         message = new textview(this);          username = new textview(this);         password = new textview(this);         login = new button(this);      }      private void createmessagetextview() {         layoutparams messagedimensions = new layoutparams(                 layoutparams.wrap_content, layoutparams.wrap_content);         messagedimensions.addrule(relativelayout.align_parent_left);         message.settext("please login first");         message.setlayoutparams(messagedimensions);     } } 

here:

    main.addview(message, messagedimensions); 

messagedimensions null because creating new object of layoutparams name messagedimensions in createmessagetextview() method instead of using messagedimensions object declared @ class level.

so, use :

  messagedimensions = new layoutparams(                     layoutparams.wrap_content, layoutparams.wrap_content);             messagedimensions.addrule(relativelayout.align_parent_left); 

in createmessagetextview() method.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -