0

I have added a LinearLayout dynamically and a TextView into it. Now I have to add the background, format them as per my requirement. So I am stuck with few questions. Here is my code:

LinearLayout parentLayout = (LinearLayout) findViewById(R.id.master);
LinearLayout Linear1 = new LinearLayout(this);
Linear1.setOrientation(LinearLayout.HORIZONTAL);
Linear1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
        LayoutParams.MATCH_PARENT));
Linear1.setId(1);
TextView tvLeft = new TextView(this);
tvLeft.setText("Hello");
tvLeft.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
        LayoutParams.WRAP_CONTENT));
Linear1.addView(tvLeft);
parentLayout.addView(Linear1);

I have few questions:

  • How can I add drawable resource as my background?

I have tried this:

Linear1.setBackgroundResource(getResources().getDrawable(R.drawable.gradient_pink));

I am getting error message by the compiler as:

The method setBackgroundResource(int) in the type View is not applicable for the arguments (Drawable)

  • How to access the element whose id is set pragmatically?
  • How to set width = 0dip?

Please help me with these question.

1 Answer 1

2

Try this

Linear1.setBackgroundResource(R.drawable.gradient_pink);

or

Linear1.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_pink));

How to access the element whose id is set pragmatically?

with the findViewById(yourid) itself

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

2 Comments

setId takes only integers. I have written setId(1) what should I write in findViewById?
findViewById also accepts int only... you should give findViewById(1)

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.