我的LinearLayout / View排列有问题。我想在我的LinearLayout和我的TextView(像WhatsApp有)之间有一个空格。我试图用LayoutParams设置边距,但它没有用。这是我的代码:
public void sendMessage(View v) {
String actualMessage = textMessage.getText().toString();
TextView message = new TextView(this);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)message.getLayoutParams();
message.setText(actualMessage);
message.setGravity(Gravity.RIGHT);
message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
message.setBackgroundColor(getResources().getColor(R.color.orange));
params.setMargins(0, 0, 0, 0);
message.setLayoutParams(params);
linearLayout.addView(message);
}
答案 0 :(得分:0)
由于这两行,你有NPE
TextView message = new TextView(this);//orphan
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
message.getLayoutParams();//how can he have a parental care
你看到了你的问题
View.getLayoutParams()
返回父级为特定孩子设置的布局参数,(-parental care)
更改为
public void sendMessage(View v) {
String actualMessage = textMessage.getText().toString();
TextView message = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.
WRAP_CONTENT);//use what you want
message.setText(actualMessage);
params.gravity = Gravity.RIGHT;
message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
message.setBackgroundColor(getResources().getColor(R.color.orange));
params.setMargins(0, 0, 0, 0);
message.setLayoutParams(params);
linearLayout.addView(message);
}
如果你使用Match_parent宽度忘记重力。
希望有所帮助