سؤال

أود أن أضيف برمجيا إلى LinearLayout بعض TextViews.وأريد أن استخدم LayoutInflater.لدي في ملف xml لتخطيط النشاط الخاص بي:

<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 يتم تجاهلها ولا أستطيع رؤية أي هوامش حول TextView المضافة.

لقد وجدت السؤال ذكري المظهر:ClassCastException عند إضافة طريقة عرض الرأس إلى ExpandableListView ولكن في حالتي لدي استثناء في السطر الأول الذي أستخدم فيه النافخ.

هل كانت مفيدة؟

المحلول

عندما تحدد طريقة العرض الجذر (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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top