NewUser
NewUser

Reputation: 3819

Adding layout properties dynamically

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:

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)

Please help me with these question.

Upvotes: 0

Views: 100

Answers (1)

Pragnani
Pragnani

Reputation: 20155

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

Upvotes: 2

Related Questions