ClassCastException when 추가 텍스트 뷰를 LinearLayout
-
11-12-2019 - |
문제
추가하고 싶다면 프로그래밍 방식으로 LinearLayout
일 TextViews
.고 사용하고 싶 LayoutInflater
.내가 내 활동에 레이아웃 xml file:
<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
/>
가 서면에서 활동은 다음과 같은 코드를 이다.
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);
textView.setText("Some text");
linearLayout.addView(textView);
나 scale.xml
파일은 다음과 같:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:drawableTop="@drawable/unit"
/>
에선 TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);
나는 치명적인 예외는 다음과 같이다.
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MyActivity}:
java.lang.ClassCastException: android.widget.LinearLayout
Caused by: java.lang.ClassCastException: android.widget.LinearLayout
때 나는 대체에서 문제가 되는 라인 linearLayout
null 없어요 어떤 예외지만, android:layout_marginLeft
고 android:layout_marginRight
에서 나 scale.xml
는 무시되고 나오지 않는 여백은 추가 텍스트 뷰.
내가 찾는 질문 드:ClassCastException when 를 추가하는 헤더를 보기 ExpandableListView 하지만 내 경우에는 예외에서 첫 번째 라인에서는 사용 inflater.
해결책
를 지정할 때 뿌리기(linearLayout
에서)전화 inflater.inflate()
, 이,팽창기에 자동으로 추가됩니다.따라서,당신은 도움을 요청할 필요가 없 addView
.또한,당신은 발견했습니다,반환되는 보트의 계층 구조( LinearLayout
).을 얻을 참조하여 TextView
자체할 수 있습니다 다음이 검색:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.scale, linearLayout, true);
TextView textView = (TextView) linearLayout.getChildAt(
linearLayout.getChildCount()-1);
textView.setText("Some text");
는 경우에 당신을 제공하 보기 android:id
특성 scale.xml 할 수 있습 검색
TextView textView = (TextView) linearLayout.findViewById(R.id.text_id);