Android setting LinearLayout background programmatically

后端 未结 6 897
一整个雨季
一整个雨季 2021-02-06 02:34

I have a situation where I need to set a background on a LinearLayout programatically.

In my layout, I am setting my background using `android:background=\"?android:att

相关标签:
6条回答
  • 2021-02-06 03:08

    try this line

    rootLayout.setBackgroundResource(d);
    

    instead of

    rootLayout.setBackgroundDrawable(d);
    
    0 讨论(0)
  • 2021-02-06 03:23

    Please try the following code.

    LinearLayout layout=(LinearLayout) findViewById(R.id.layoutImage);
    layout.setBackgroundResource(R.drawable.bg);
    
    0 讨论(0)
  • 2021-02-06 03:25

    It's a bad idea doing it the way the accepted answer tells you to. The problem is that you also need to call the list's onItemCheckedStateChanged to update what's needed (the action bar title for example).

    In that case all you need to do is simply call getListView().setItemChecked(position, true); when the item is checked and getListView().setItemChecked(position, false); when it's not checked.

    0 讨论(0)
  • 2021-02-06 03:30

    I had the same problem and I fixed it using this piece of code.

    The android.R.attr.* are pointers to the in a theme and not to the actual drawable resource defined. You have to use the TypedArray to access the id.

    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 detects SDK upper and worked fine.

    0 讨论(0)
  • 2021-02-06 03:30

    You can use something like this

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

    0 讨论(0)
  • 2021-02-06 03:32

    try this

    rootLayout.setBackgroundResource(R.drawable.image);
    
    0 讨论(0)
提交回复
热议问题