1

I have 2 TextViews and I want to add those to LinearLayout, but when I ran the project, only one TextView appreared.

Here's my code:

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        TextView textView = new TextView(this);
        textView.setText("Thank you, Jesus!");
        textView.setTextColor(Color.BLACK);

        TextView textView2 = new TextView(this);
        textView.setText("Dont give up on me!");
        textView.setTextColor(Color.BLACK);

        LinearLayout layout = new LinearLayout(this);
        layout.setBackgroundColor(Color.WHITE);

        layout.addView(textView);
        layout.addView(textView2);

        setContentView(layout);
    }

}

After running, textView2 was the only view present in the LinearLayout.

Can someone explain to me what was going on?

1 Answer 1

1

Use textView2 for calling setText and setTextColor method for textView2 because currently you are using textView :

    TextView textView2 = new TextView(this);
    textView2.setText("Dont give up on me!");
    textView2.setTextColor(Color.BLACK);

Suggestion also set height/width for all views by calling setLayoutParams method

Another Suggestion : Add Orientation to Linear layout by using: layout.setOrientation(LinearLayout.VERTICAL);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.