Configure Android LinearLayout programmatically

I have a situation where I need to set the background in LinearLayout programmatically.

In my layout, do I set my background using "android: background ="? android: attr / activatedBackgroundIndicator ", but I want to install this programmatically:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myLayoutId" android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="left|center" android:paddingBottom="5dip" android:paddingLeft="5dip" android:background="?android:attr/activatedBackgroundIndicator" android:paddingTop="5dip" > 

I tried using:

 Drawable d = getActivity().getResources().getDrawable(android.R.attr.activatedBackgroundIndicator); rootLayout.setBackgroundDrawable(d); 

But he is falling. Any ideas?

Edit: I also tried using:

 rootLayout.setBackgroundResource(android.R.attr.activatedBackgroundIndicator); 10-08 15:23:19.018: E/AndroidRuntime(11133): android.content.res.Resources$NotFoundException: Resource ID #0x10102fd 
+7
source share
6 answers

I had the same problem and fixed it with this code snippet.

android.R.attr. * are pointers to a topic in a topic, and not to a specific resource. You must use TypedArray to access the identifier.

 theView = this.inflater.inflate(R.layout.list_row_job_favorited, null); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { TypedArray a = mContext.obtainStyledAttributes(new int[] { android.R.attr.activatedBackgroundIndicator }); int resource = a.getResourceId(0, 0); //first 0 is the index in the array, second is the default value a.recycle(); theView.setBackground(mContext.getResources().getDrawable(resource)); } 

I used this in my custom list adapter when I discovered the SDK and worked fine.

+13
source

try this line

 rootLayout.setBackgroundResource(d); 

instead

 rootLayout.setBackgroundDrawable(d); 
+5
source

try it

 rootLayout.setBackgroundResource(R.drawable.image); 
+3
source

This is a bad idea that does it as the accepted answer says. The problem is that you also need to call the onItemCheckedStateChanged list to update what you need (e.g. the title of the action bar).

In this case, all you have to do is just call getListView().setItemChecked(position, true); when the item is checked, and getListView().setItemChecked(position, false); if it is not installed.

+1
source

You can use something like this

TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.selectableItemBackgroun d, outValue, true); view.setBackgroundResource(outValue.resourceId);

+1
source

Please try the following code.

 LinearLayout layout=(LinearLayout) findViewById(R.id.layoutImage); layout.setBackgroundResource(R.drawable.bg); 
+1
source

All Articles