9

プログラムで LinearLayout に背景を設定する必要がある状況があります。

私のレイアウトでは、「android:background="?android:attr/activatedBackgroundIndicator」を使用して背景を設定していますが、これをプログラムで設定したい:

<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" >

私は使用してみました:

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

しかし、それはクラッシュします。何か案は?

編集:私も使用してみました:

rootLayout.setBackgroundResource(android.R.attr.activatedBackgroundIndicator);

10-08 15:23:19.018: E/AndroidRuntime(11133): android.content.res.Resources$NotFoundException: Resource ID #0x10102fd
4

6 に答える 6

14

同じ問題が発生し、このコードを使用して修正しました。

android.R.attr。*は、テーマ内のへのポインターであり、定義された実際の描画可能なリソースへのポインターではありません。IDにアクセスするには、 TypedArrayを使用する必要があります。

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));
}

SDKアッパーを検出し、正常に動作したときに、カスタムリストアダプターでこれを使用しました。

于 2013-02-19T11:30:04.927 に答える
6

この行を試してください

rootLayout.setBackgroundResource(d);

それ以外の

rootLayout.setBackgroundDrawable(d);
于 2012-10-08T12:13:19.533 に答える
4

これを試して

rootLayout.setBackgroundResource(R.drawable.image);
于 2012-10-08T12:17:21.320 に答える
2

受け入れられた答えがあなたに指示する方法でそれを行うのは悪い考えです。問題は、リストを呼び出して、onItemCheckedStateChanged必要なもの (アクション バーのタイトルなど) を更新する必要があることです。

getListView().setItemChecked(position, true);その場合、アイテムがチェックされているときとチェックされていないときに呼び出すだけですgetListView().setItemChecked(position, false);

于 2015-05-21T14:21:28.117 に答える
1

このようなものを使用できます

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

于 2015-10-17T18:54:50.383 に答える