-1

I have a problem with my LinearLayout/View arrangement. I would like to have a space between my LinearLayout and my TextView (Like WhatsApp has). I tried to set the margins with LayoutParams but it didn't work out. Here my code:

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);
}
Yassin Hajaj
  • 20,020
  • 9
  • 41
  • 81
iHuba
  • 31
  • 4
  • Post full exception stack. – kosa Sep 22 '15 at 20:59
  • If you want a space, then why are you setting the margins to 0? – Buddy Sep 22 '15 at 21:04
  • only for testing if it would compile. The stack isn't properly formatted in the comment section any ideas how i can fix it? – iHuba Sep 22 '15 at 21:07
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Phantômaxx Sep 22 '15 at 22:01

1 Answers1

0

You are having NPE because of this two lines

TextView message = new TextView(this);//orphan
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
             message.getLayoutParams();//how can he have a parental care

have you seen your problem

View.getLayoutParams() returns the Layout parameters that the parent has set for a particular child, (-parental care)

change to this

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);
}

if you use Match_parent for width forget about gravity.

Hope it helps

Elltz
  • 10,073
  • 3
  • 26
  • 55