마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

View를 상속하는 커스텀뷰를 main.xml에서 생성하고 findviewbyid로 객체를 얻어내면 에러가 납니다

0 추천

메인 액티비티 클래스에서 커스텀뷰를 정의하고
 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TestView view= (TestView)findViewById(R.id.xml_view);
    }

    public class TestView extends View {

        public TestView(Context context) {
            super(context);
        }

        @Override
        public void draw(Canvas canvas) {
            super.draw(canvas);
            Paint paint = new Paint();

            canvas.drawColor(Color.RED);
            paint.setColor(Color.BLUE);
            canvas.drawCircle(100,100,500,paint);
        }
    }
}



아래와 같이 메인 xml에 커스텀 뷰를 작성했는데
 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.study.high5light.myquestion.MainActivity">

    <View
        android:class = "com.study.high5light.myquestion.MainActivity.TestView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/xml_view"/>

</android.support.constraint.ConstraintLayout>



 

findbyviewid로 객체를 얻으려고 하변 빌드 에러가 납니다

왜 그런가요????

알려주시면 감사하겠습니다

high555light (140 포인트) 님이 2018년 1월 13일 질문

1개의 답변

0 추천

이렇게 쓰려고 하셨던거 아닌지요?

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.study.high5light.myquestion.MainActivity">
 
    <com.study.high5light.myquestion.MainActivity.TestView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/xml_view"/>
 
</android.support.constraint.ConstraintLayout>

 

디자이너정 (42,810 포인트) 님이 2018년 1월 13일 답변
감사합니다
적어주신대로 하고,
TestView를 메인의 내부클래스 에서 보통 클래스로 변경
모든 생성자를 포함하니 잘 동작합니다
...