java - 函数内的 LayoutParam 问题
问题描述
我试图通过将 RelativeLayout.LayoutParams 放在函数中来清理我的 java 代码,这样我就不必每次添加新东西时都创建新的 layoutparams。
问题:我收到错误代码
Unable to start activity ComponentInfo{onedevz.com.noct/onedevz.com.noct.MainActivity}: java.lang.NullPointerException: Layout parameters cannot be null
它说我没有布局参数,即使我有一个并且我在将它放入按钮之前调用了它。这是代码
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);
}
}
任何帮助将不胜感激,谢谢。
解决方案
您的LayoutParameters
lp1,lp2,lp3,lp4 尚未初始化。初始化它们,然后将其设置为TextView
.
推荐阅读
- oracle-apex - 如何通过 ssh 进入 Oracle DB 开发人员 VM
- raspberry-pi - 如何在树莓派上实现信标?
- node.js - npm audit 在我升级包后抱怨漏洞
- java - 如何从适配器类中的 Json 对象中排序项目?
- c++ - 如何使用 QOpenGLBuffer:: PixelUnpackBuffer
- trackpy - 改变 tp.annonate 中的粒子颜色
- java - 在 Atom 的初始化脚本中指定路径
- eclipse - HBox setMargin错误(HBox类型的静态方法设置边距(节点,昆虫)应该以静态方式访问)用于类分配
- mysql - 如何从 MySQL 中的列中选择 10 个最高值?
- bash - 将位置参数传递给包含 `.` 点的 bash 函数