2016-03-19 7 views
4

solidの色をのFragmentに変更しようとしています。Androidでシェイプのソリッドカラーをプログラム的に変更するにはどうすればよいですか?

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:id="@+id/icon_circle_background"> 
     <shape xmlns:android="http://schemas.android.com/apk/res/android" 
      ...> 
      <solid android:color="@color/md_cyan_400"/> 
     </shape> 
    </item> 
    <item 
     ... 
    </item> 
</layer-list> 

私は自分のコードからアクセスできないようですし、私はすでに、スタックオーバーフロー上の次の答え試してみました:

Set android shape color programmatically

How to change shape color dynamically?

Change shape solid color at runtime inside Drawable xml used as background

なしにこれらの仕事はかなり古いです。私は色変更しよう

フラグメント:

public class GameFragment extends Fragment { 
    private Theme currentTheme; 
    private Circle currentCircle; 
    private int currentOrganisationId; 
    private List<Card> circleCards; 
    private List<ImageButton> circleButtons; 
    private int viewHeight; 
    private int viewWidth; 
    private int marginCard; 
    private int[] tableStarts; 
    private RelativeLayout background; 
    private ViewTreeObserver vto; 

    public GameFragment() { 
     circleCards = new ArrayList<>(); 
     circleButtons = new ArrayList<>(); 
     tableStarts = new int[9]; 
    } 

    //... 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_game, container, false); 
     ... 
     background = setBackground(rootView); 
     circleCards = currentCircle.getCards(); 

     return rootView; 
    } 

    //... 

    private void drawCards() { 
     circleButtons = new ArrayList<>(); 
     for (Card card : circleCards) { 
      ImageButton myImageButton = new ImageButton(this.getContext()); //generate ImageButton 
      myImageButton.setId(card.getCardId()); //Set Id of button 
      myImageButton.setBackgroundResource(R.drawable.circle_card_icon); 

      //set random color to shape 
      ... 
     } 
    } 
} 
+0

「かなり古くなった」とはどういう意味ですか?彼らはうまくいくはずです。 –

+0

@Bob Malooga、それを試しても、私にこのhttps://goo.gl/fXL4Peコードを与えてくれます:http://pastebin.com/KqNNTDnU – Edward

答えて

1
View v = findViewById(R.id.layout_id); 
LayerDrawable shape= (LayerDrawable)v.getBackground(); 
shape.setColor(Color.Black); 
1

使用は、この:このそれはスローされません

GradientDrawable bgShape = (GradientDrawable)view.getBackground().getCurrent(); 
bgShape.setColor(Color.BLACK); 

.getCurrentは、選択した描画可能なレイヤリストに

使用を与えますjava.lang.ClassCastException:android.graphics.drawable.GradientDrawableをandroid.graにキャストできませんphics.drawable.ShapeDrawable例外。

それは私にとって完璧に機能します。

関連する問題