-1

I've got a TextView that crashes the app when trying to setText. I'm not using the XML layout and have set a custom view to handle everything. Obviously the app crashes when the screen is touched after the app is initalized.

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout lv = new LinearLayout(this);
    lv.setOrientation(LinearLayout.VERTICAL);
    mView = new MyView(this);
    TextView tvX = new TextView(this);
    lv.addView(tvX);
    lv.addView(mView);
    lv.setBackgroundColor(Color.GRAY);
    tvX.setTextColor(Color.WHITE);
    tvX.setText("Ahmad");
    setContentView(lv);
    mView.requestFocus();


public class MyView extends View {
    private TextView tvX;

    public void setTextView(TextView tv){
        tvX = tv;
    }

    @Override public boolean onTouchEvent(MotionEvent event) {
        tvX.setText("123"); 
    }

Any help is appreciated!

EDIT 1

08-27 00:39:49.859: E/MessageQueue-JNI(510):    at co.projx.touchpaint.TouchPaint$MyView.onTouchEvent(TouchPaint.java:286)
08-27 00:39:49.874: E/AndroidRuntime(510):  at co.projx.touchpaint.TouchPaint$MyView.onTouchEvent(TouchPaint.java:286)
ahmadux
  • 2,667
  • 3
  • 17
  • 15

1 Answers1

1

Your problem is the same as here: View becomes null on setText

You're missing the LayoutParams (WRAP_CONTENT, WRAP_CONTENT).

Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Where should I add that exactly in my code? I added it under LinearLayout lv and it's crashing still. I set it as `lv.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));` – ahmadux Aug 26 '14 at 21:45
  • Considering you are making the layout programatically (who knows why), the linear layout is missing `FILL_PARENT, WRAP_CONTENT` and your textview is missing `WRAP_CONTENT, WRAP_CONTENT`, and I'm not sure what `myView` is. – EpicPandaForce Aug 26 '14 at 21:47
  • It's a paint app, so the view was made programatically. I'm very new to Android. I would appreciate a code suggestion to fix my problem. Thanks for the help! – ahmadux Aug 26 '14 at 21:53
  • You need to provide them layout parameters. – EpicPandaForce Aug 27 '14 at 07:13