I am trying to clean my java code by placing RelativeLayout.LayoutParams inside a function, so that I don't have to create new layoutparams everytime I add new thing.
The problem: I got an error code
Unable to start activity ComponentInfo{onedevz.com.noct/onedevz.com.noct.MainActivity}: java.lang.NullPointerException: Layout parameters cannot be null
it says I got no layout param even though I do have one and I called it before I placed it into a Button. here is the code
public class MainActivity extends AppCompatActivity {
MicButton micbutton;
Button menuBtn,onBtn;
EditText text;
RelativeLayout relativeLayout;
RelativeLayout.LayoutParams lp1,lp2,lp3,lp4;
boolean clicked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Defining the layout parameters of the TextView
placement(lp1,100,100,0,200,40,0,RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);
placement(lp2,100,100,0,350,40,0,RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);
placement(lp3,100,100,0,500,40,0,RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.ALIGN_PARENT_LEFT);
placement(lp4,100,ViewGroup.MarginLayoutParams.MATCH_PARENT,150,0,40,0,RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.CENTER_HORIZONTAL);
setParameter();
addView();
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
void placement(RelativeLayout.LayoutParams name,int height,int width,int topMargin,int bottomMargin,int leftMargin,int rightMargin,int rule1,int rule2){
name = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
name.addRule(rule1);
name.addRule(rule2);
name.leftMargin = leftMargin;
name.bottomMargin = bottomMargin;
name.height = height;
name.width = width;
}
void setParameter(){
// Setting the parameters on the TextView
micbutton.setLayoutParams(lp1);
onBtn.setLayoutParams(lp2);
menuBtn.setLayoutParams(lp3);
text.setLayoutParams(lp4);
}
void addView(){
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(micbutton);
relativeLayout.addView(text);
}
}
Any help will be appreciated, Thanks.
Your LayoutParameters
lp1,lp2,lp3,lp4 have not been initialized. Initialize them and then set it to the TextView
.