2014-07-08 2 views
1

제목을 사용하십시오 -이 질문에 단어를 쓰는 방법을 모르십니까?XML 드로어 블 리소스의 요소 속성에 액세스

나는 안에 rectangle.xml이라는 파일을 만들었습니다. 그것은 매우 기본적인 직사각형 모양입니다, 나는 사용자 지정 목록보기 내에서 ImageView와 함께 사용하고 있습니다.

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
    <solid android:color="#FF0000" /> 
    <corners android:radius="4dp"/> 
</shape> 

하는 것은 너무처럼 사용 :

<ImageView 
    android:id="@+id/row_colorRect" 
    android:layout_width="24dp" 
    android:layout_height="match_parent" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true" 
    android:src="@drawable/rectangle" /> 

가 나는 즉석에서 색상을 변경할 수 있도록 그 사각형의 solid 속성에 액세스 할 수 있어야합니다. 나는 ImageView를 통해 그 속성에 접근 할 수 없다. 그래서 나는 어떻게 든 ImageView의 자식을 파헤 치고, 모양을 찾고, 그런 식으로 바꾸어야한다고 상상한다.

어떻게해야합니까?

감사합니다.

+1

나는 t 해본 적이 그의 것 그러나 당신이 시도 할 수있는 무엇이 분리되는 재산을 가진 2 개의 다른 모양을 창조하고 그 후에 ImageView의 근원을 프로그램으로 변화시키기위한 것이다. – Setu

답변

1

방금 ​​시도하고 관리했습니다. 당신의 rectangle.xml 자원을 나타내는 ImageViewGradientDrawable를 액세스

ImageView imageView = (ImageView) findViewById(R.id.row_colorRect); 
((GradientDrawable) imageView.getDrawable()).setColor(Color.RED); 

, 당신은 다른 속성들 사이의 솔리드 색상을 변경할 수 있습니다.

+0

이것은 훌륭하게 작동했습니다. 감사합니다. 나는이 잘못에 접근하고 있는가? 난 그냥 각 ListView 행에 색깔의 표시기를 원하고 행의 "상태"에 따라 색상을 바꿀 수 있기를 원합니다. 그러나 대답 한 모두는 그런 일을 시도한 적이없는 것 같습니다. 내가이 일을 비정상적인 방식으로 수행하고 있다고 생각하게 만듭니다. – user1003916

0

이 방법을 시도해보고 문제를 해결하는 데 도움이되기를 바랍니다.

shape.xml (그리기)

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
    <solid android:color="#FF0000" /> 
    <corners android:radius="4dp"/> 
</shape> 

main.xml에

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center"> 

    <ImageView 
     android:id="@+id/imageView" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:background="@drawable/shape"/> 

</LinearLayout> 

MyActivity.java

public class MyActivity extends Activity { 

    private ImageView imageView; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     imageView = (ImageView) findViewById(R.id.imageView); 

     imageView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       GradientDrawable sd = (GradientDrawable) imageView.getBackground().mutate(); 
       sd.setColor(Color.parseColor("#CCC111")); 
       sd.invalidateSelf(); 
      } 
     }); 
    } 

}