Проблемы с setBackgroundResource

У меня странные проблемы с setBackgroundResource. По какой-то причине, когда я запускаю фоллинг-код, он не устанавливает фоновый фон.

layoutId - это идентификатор макета, который я хочу добавить к другому. Это выполняется до этого, а затем я запускаю этот код.

viewToBorderId - это идентификатор представления в этом макете. Именно вокруг этой точки зрения я хочу установить границу.

    ViewGroup contentView = (ViewGroup) this.getLayoutInflater().inflate(layoutId, null);
    RelativeLayout contentScreenRoot = (RelativeLayout) this.findViewById(R.id.content_screen_root);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        ((ScrollView) contentScreenRoot.findViewById(R.id.content_screen_scroll_view)).getLayoutParams());
    lp.addRule(RelativeLayout.BELOW, R.id.content_screen_user_details);
    lp.setMargins(2, 0, 2, 0);

    contentScreenRoot.addView(contentView, lp);
    ViewGroup contentViewParent = (ViewGroup) this.getLayoutInflater().inflate(layoutId, null);
    ViewGroup contentView = (ViewGroup) contentViewParent.findViewById(viewToBorderId);

    GradientDrawable gd ;
    gd = (GradientDrawable) contentView.getBackground();
    if (gd == null){
        contentView.setBackgroundResource(R.drawable.content_screen_borders_no_rounding);
        gd = (GradientDrawable) contentView.getBackground();
    }

    gd.setCornerRadii(new float[]{0,0,0,0,0,0,20-3,20-3});

    contentView.setBackgroundDrawable(gd);

R.drawable.content_screen_borders_no_rounding

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <stroke
        android:width="@dimen/content_screen_scroll_view_border"
        android:color="@color/content_screen_scroll_view_border"
        />
    <padding
        android:left="0dip"
        android:top="@dimen/content_screen_scroll_view_border"             
        android:right="0dip" 
        android:bottom="@dimen/content_screen_scroll_view_border"
        />
    <gradient
        android:angle="270"
        android:startColor="@color/listview_selected_item_start"
        android:endColor="@color/listview_selected_item_end"
        android:type="linear"
        />
</shape>

Странно то, что, если я заранее установил фон с помощью android:background="@drawable/content_screen_borders_no_rounding", то он работает нормально. Граница есть, и когда я делаю последний бит кода для округления угла, это работает. Это только когда я делаю все из кода, это терпит неудачу.

"Базовый" макет, в который вставляются другие макеты:

<?xml version="1.0" encoding="UTF-8"?>

<RelativeLayout
    android:id="@+id/content_screen_secondary_title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dip"
    >

    <ImageView 
        android:id="@+id/content_screen_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="20dip"
        android:paddingRight="20dip"
        android:layout_alignParentLeft="true"
        android:gravity="top|left"
        />

    <!-- The following RelativeLayout container is required to force the Hebrew text on some devices to appear at the right of the background image instead of the left on certain devices -->
    <RelativeLayout
        android:id="@+id/content_screen_helper"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/content_screen_icon"
        android:background="@drawable/title_bg"
        android:layout_alignParentRight="true"
        android:gravity="center_vertical"
        android:layout_centerVertical="true"
        >

        <TextView
            android:id="@+id/content_screen_title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/content_text_color"
            android:textSize="18sp"
            android:textStyle="bold"
            android:gravity="center_vertical|right"
            android:layout_alignParentRight="true"
            android:paddingRight="25dip"
            />

    </RelativeLayout>

</RelativeLayout>

<RelativeLayout
    android:id="@+id/content_screen_user_details"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/user_details_bg"
    android:layout_below="@id/content_screen_secondary_title"
    android:layout_marginBottom="4dip"
    android:layout_marginLeft="20dip"
    android:visibility="gone"
    >
    <!-- value for visibility can be either 'visible' or 'gone' -->

    <TextView
        android:id="@+id/content_screen_user_name_prompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:paddingRight="25dip"
        android:text="@string/content_screen_name_prompt"
        android:textSize="12sp"
        android:textColor="@color/content_text_color"
        android:layout_centerVertical="true"
        android:gravity="center_vertical"
        />
    <TextView
        android:id="@+id/content_screen_user_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/content_screen_user_name_prompt"
        android:paddingRight="5dip"
        android:textSize="12sp"
        android:textColor="@color/content_text_color"
        android:layout_centerVertical="true"
        android:gravity="center_vertical"
        />
    <TextView
        android:id="@+id/content_screen_user_id_prompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/content_screen_user_id"
        android:layout_centerVertical="true"
        android:paddingLeft="5dip"
        android:text="@string/content_screen_id_prompt"
        android:textSize="12sp"
        android:textColor="@color/content_text_color"
        />
    <TextView
        android:id="@+id/content_screen_user_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:paddingLeft="20dip"
        android:textSize="12sp"
        android:textColor="@color/content_text_color"
        />

</RelativeLayout>

<ScrollView
    android:id="@+id/content_screen_scroll_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/content_screen_user_details"
    android:background="@drawable/content_screen_borders"
    android:layout_marginRight="10dip"
    android:layout_marginLeft="10dip"
    android:layout_marginBottom="10dip"
    android:layout_marginTop="@dimen/content_screen_scroll_view_margintop"
    android:visibility="gone"
    >
    <!-- Set visibility to gone, until the user calls the method: setMainContent(), which causes this ScrollView to become visible and also assigns it with its content -->

</ScrollView>

<!-- The following RelativeLayyout container is required to make the Hebrew text on some devices to start at the right of the background image instead of the left -->
<RelativeLayout
    android:id="@+id/content_screen_details_container"
    android:layout_width="150dip"
    android:layout_height="wrap_content"
    android:layout_marginRight="10dip"
    android:layout_above="@id/content_screen_scroll_view"
    android:background="@drawable/details_bg"
    android:gravity="center_vertical|right"
    android:layout_alignParentRight="true"
    android:visibility="invisible"
    >
    <!-- Value for visibility can be 'visible' or 'invisible' -->

    <TextView
        android:id="@+id/content_screen_details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/content_text_color"
        android:layout_centerVertical="true"
        android:gravity="center_vertical|right"
        android:paddingRight="10dip"
        />

</RelativeLayout>

Затем я вызываю код выше, чтобы добавить что-то.

Это то, что я хотел бы добавить:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >

    <ListView
        android:id="@+id/searchable_list_list_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:paddingLeft="2dip" 
        android:paddingRight="2dip" 
        android:dividerHeight="1dip"
        android:footerDividersEnabled="true"
        android:listSelector="@drawable/listview_selected_item_background"
        android:fadingEdge="none"
        android:cacheColorHint = "#00000000"

        >

    </ListView>


</LinearLayout>

Я бы назвал вышеуказанный метод, передавая макет в качестве первого идентификатора и идентификатор "searchable_list_list_view" в качестве отправки. Это говорит о том, чтобы вставить этот макет на экран и поставить рамку вокруг этого конкретного вида.

1 ответ

Решение

theblitz,

Вы заявляете, что только после того, как вы попытаетесь сделать все это в коде, оно не будет работать. Это подразумевает, что вы изменили код для улучшения функции. После того, как вы тщательно проанализировали свой код, я считаю, что здесь ошибка в том, что вы дважды надуваете представление, добавляете его один раз и меняете фон не добавленного представления. Это, вероятно, произошло при внесении изменений. Я объясню:

В начале вашего блока:

ViewGroup contentView = (ViewGroup) this.getLayoutInflater().inflate(layoutId, null);

Чуть позже вы добавляете новый вид:

contentScreenRoot.addView(contentView, lp);

Вы еще ничего не сделали, поэтому мы переходим к следующей части.

ViewGroup contentViewParent = (ViewGroup) this.getLayoutInflater().inflate(layoutId, null);

Он имеет тот же идентификатор, что и contentView, поэтому мы знаем, что вы надуваете тот же макет Тем не менее, нет addView когда-либо исполняется, так что он просто сидит и исчезнет через некоторое время. Очевидно, что родитель и представление не могут быть одинаковыми, поэтому вы получили фактическое представление от своего родителя.

ViewGroup contentView = (ViewGroup) contentViewParent.findViewById(viewToBorderId);

Вот и все, кроме одной проблемы. Во-первых, contentView уже был определен. Во-вторых, он находит представление внутри группы, которое не было добавлено. Он меняет фон нового contentView, но затем ничего не делает, потому что он никогда не отображается.

Предлагаемое решение (я):

Измените свой код на следующий (комментарии объясняют изменения)

// --> Rename this variable. It IS the inflated Parent and we only need to do this once.
  ViewGroup contentViewParent = (ViewGroup) this.getLayoutInflater().inflate(layoutId, null);
  RelativeLayout contentScreenRoot = (RelativeLayout) this.findViewById(R.id.content_screen_root);
  RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
    ((ScrollView) contentScreenRoot.findViewById(R.id.content_screen_scroll_view)).getLayoutParams());
  lp.addRule(RelativeLayout.BELOW, R.id.content_screen_user_details);
  lp.setMargins(2, 0, 2, 0);

// --> Align the addView statement to use the new name
  contentScreenRoot.addView(contentViewParent, lp);

// --> Delete this line completely. (see? its the same ID)
//ViewGroup contentViewParent = (ViewGroup) this.getLayoutInflater().inflate(layoutId, null);

// Now this should be using the added ViewGroup, rather than the unadded one.
// AND it is not being redefined, like it was before.
  ViewGroup contentView = (ViewGroup) contentViewParent.findViewById(viewToBorderId);

  GradientDrawable gd ;
  gd = (GradientDrawable) contentView.getBackground();
  if (gd == null){
      contentView.setBackgroundResource(R.drawable.content_screen_borders_no_rounding);
      gd = (GradientDrawable) contentView.getBackground();
  }

gd.setCornerRadii(new float[]{0,0,0,0,0,0,20-3,20-3});

contentView.setBackgroundDrawable(gd);

Надеюсь это поможет,

FuzzicalLogic

Другие вопросы по тегам