簡體   English   中英

FindViewById返回NULL滾動視圖

[英]FindViewById returns NULL Scroll View

我正在開發一個android應用程序,我有這個問題。 我想在滾動視圖中動態添加復選框,該對話框將顯示在對話框中。 問題是通過此表達式時layout為null ScrollView layout = (ScrollView) findViewById(R.layout.custom);

這是功能。

private void openCustomMenu() {
        // TODO Auto-generated method stub


        ScrollView layout = (ScrollView) findViewById(R.layout.custom);
        layout.removeAllViews();
        for (String name : StopNames){
            CheckBox checkbox = new CheckBox(this);
            checkbox.setText(name);
            checkbox.setTextColor(getResources().getColor(R.color.white));
            layout.addView(checkbox);
        }

        final Dialog dialog = new Dialog(this);
        dialog.setContentView(layout);
        dialog.setTitle("Bus Stops");
    }

這是我的xml文件。

  <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/custom"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

    </ScrollView>

Thank you for you help !

編輯:新的XML

 <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/custom">

        </LinearLayout>


</ScrollView>

和新功能。

private void openCustomMenu() {




final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.custom);
        dialog.setTitle("Bus Stops");

        LinearLayout layout = (LinearLayout) dialog.findViewById(R.id.custom);      
        layout.removeAllViews();
        for (String name : StopNames){
            CheckBox checkbox = new CheckBox(this);
            checkbox.setText(name);
            checkbox.setTextColor(getResources().getColor(R.color.white));
            layout.addView(checkbox);
        }



    }

更改findViewById(R.layout.custom); findViewById(R.id.custom); ,因此請在您的代碼中執行以下操作:

 ScrollView layout = (ScrollView) findViewById(R.id.custom);

你想獲得idlayouts從,而不是ids

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM