'int android.view.View.getVisibility()'在null对象引用onphone但不在模拟器中

时间:2017-02-13 20:54:52

标签: android

我收到一个java.lang.NullPointerException:当我在我的android marshmallow手机上加载我的应用程序时,尝试在空对象引用错误上调用虚拟方法'int android.view.View.getVisibility()'但它没有在avd模拟器上 这个问题是不同的,因为错误似乎只发生在Android 6.1或更低版本。

AlarmReceiver.java

package com.example.ersch.noschoolcalculator;

public class MainActivity extends AppCompatActivity {
private String htmlContentInStringFormat;
private TextView Day1a;
private TextView Day1b;
private TextView Day1c;
private TextView Day2a;
private TextView Day2b;
private TextView Day2c;
private Boolean weather_gov_error;
private TextView ERROR_LOG;
private String first;
public Boolean fatal_error;
private String second;
private String day1a;
private String[] day1b;
private String day1c;
private String day2c;
private String day2a;
private String[] day2b;
private PendingIntent pendingIntent;
private AlarmManager manager;
private String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
private StringBuilder sb = new StringBuilder(14);
private Map<String, String> firstlist = new HashMap<>();
private Map<String, String> secondlist = new HashMap<>();
public static void longInfo(String str) {
    if(str.length() > 4000) {
        Log.i("Message:", str.substring(0, 4000));
        longInfo(str.substring(4000));
    } else
        Log.i("Message:", str);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //executes jsoup
    JsoupAsyncTask jsoupAsyncTask = new JsoupAsyncTask();
    jsoupAsyncTask.execute();
    //initializes layout

    setContentView(R.layout.activity_main);
    Day1a = (TextView)findViewById(R.id.Day1a);
    Day1b = (TextView)findViewById(R.id.Day1b);
    Day1c = (TextView)findViewById(R.id.Day1c);
    Day2a = (TextView)findViewById(R.id.Day2a);
    Day2b = (TextView)findViewById(R.id.Day2b);
    Day2c = (TextView)findViewById(R.id.Day2c);
    ERROR_LOG = (TextView)findViewById(R.id.ERROR_LOG);
    ERROR_LOG.setVisibility(View.INVISIBLE);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    //button click

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Refreshing", Snackbar.LENGTH_SHORT)
                    .setAction("Action", null).show();
            longInfo("Refreshing");
            JsoupAsyncTask jsoupAsyncTask = new JsoupAsyncTask();
            jsoupAsyncTask.execute();
        }

    });


}
@Override
public void onResume(){
    super.onResume();
    Intent alarmIntent = new Intent(this, AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
public void startAlarm(View view) {
    manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    int interval = 10000;

    manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
    Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    longInfo("Alarm Set");
}
public void cancelAlarm(View view) {
    if (manager != null) {
        manager.cancel(pendingIntent);
        Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
        longInfo("Alarm Canceled");
    }
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
public static boolean isListContainMethod(List<String> arraylist,String value) {
    for (String str : arraylist) {
        if (!str.toLowerCase().contains(value)) {
            return false;
        }
    }
    return true;
}
public class JsoupAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {

            String loginFormUrl = "https://www.snowdaycalculator.com/Account/login.php";
            String loginActionUrl = "https://www.snowdaycalculator.com/prediction.php?zipcode=10562&snowdays=0&extra=0&";
            String email = "erschmny@gmail.com";
            String passinstr = "email";
            String password = "ltlake66";
            HashMap<String, String> cookies = new HashMap<>();
            HashMap<String, String> formData = new HashMap<>();
            Connection.Response loginForm = Jsoup.connect(loginFormUrl).method(Connection.Method.GET).execute();
            Document loginDoc = loginForm.parse(); // this is the document that contains response html
            cookies.putAll(loginForm.cookies());
            formData.put("passInstr", "password");
            formData.put("email", email);
            formData.put("password", password);
            formData.put("back", "");
            Connection.Response homePage = Jsoup.connect(loginActionUrl)
                    .cookies(cookies)
                    .data(formData)
                    .method(Connection.Method.POST)
                    .execute();


            htmlContentInStringFormat = homePage.parse().html();
            //longInfo(htmlContentInStringFormat);
            String[] lines = htmlContentInStringFormat.split("\\r?\\n");
            Pattern p = Pattern.compile("(theChance\\[)[0-9]{5,11}] = -?\\d*\\.?\\d+E*\\+*\\d*;");
            int x = 0;
            for( int i = 0; i < lines.length - 1; i++) {
                Matcher m = p.matcher(lines[i]);
                if (m.find()) {
                    if (x == 0) {
                        first = lines[i];
                        x += 1;
                    }
                    else{
                        second = lines[i];
                    }
                }

            }
            longInfo(first);
            if (first != null & second != null){
                String regex = "[0-9]{8,11}";
                Matcher m = Pattern.compile(regex).matcher(first);
                if (m.find()) {
                    firstlist.put("date",Long.toString(Math.round(Double.parseDouble(m.group()))));
                }
                String regex2 = "-?\\d*\\.?\\d*;";
                Matcher m2 = Pattern.compile(regex2).matcher(first);
                if (m2.find()) {
                    firstlist.put("chance",Long.toString(Math.round(Double.parseDouble(m2.group().substring(0, m2.group().length()-1)))));

                }
                String regex3 = "[0-9]{8,11}";
                Matcher m3 = Pattern.compile(regex3).matcher(second);
                if (m3.find()) {
                    secondlist.put("date",Long.toString(Math.round(Double.parseDouble(m3.group()))));
                }
                String regex4 = "-?\\d*\\.?\\d*;";
                Matcher m4 = Pattern.compile(regex4).matcher(second);
                if (m4.find()) {
                    secondlist.put("chance",Long.toString(Math.round(Double.parseDouble(m4.group().substring(0, m2.group().length()-1)))));
                }

                sb.setLength(0);
                day1a = firstlist.get("date");
                day1b = day1a.split("(?!^)");
                sb.append(day1b[0]).append(day1b[1]).append(day1b[2]).append(day1b[3]);
                firstlist.put("year", sb.toString());
                sb.setLength(0);
                sb.append(day1b[4]).append(day1b[5]);
                firstlist.put("month", sb.toString());
                sb.setLength(0);
                sb.append(day1b[6]).append(day1b[7]);
                firstlist.put("day", sb.toString());
                longInfo(firstlist.toString());


                day2a = secondlist.get("date");
                day2b = day2a.split("(?!^)");
                sb.setLength(0);
                sb.append(day2b[0]).append(day2b[1]).append(day2b[2]).append(day2b[3]);
                secondlist.put("year", sb.toString());
                sb.setLength(0);
                sb.append(day2b[4]).append(day2b[5]);
                secondlist.put("month", sb.toString());
                sb.setLength(0);
                sb.append(day2b[6]).append(day2b[7]);
                secondlist.put("day", sb.toString());
                longInfo(secondlist.toString());
                htmlContentInStringFormat = homePage.parse().html();
                lines = htmlContentInStringFormat.split("\\r?\\n");
                p = Pattern.compile("(1.5em\">)|(0.85em\")");
                x = 0;
                for( int i = 0; i < lines.length - 1; i++) {
                    m = p.matcher(lines[i]);
                    if (m.find()) {
                        if (x == 0) {
                            first = lines[i];
                            longInfo(first);
                            x += 1;
                        }
                        else{
                            second = lines[i];
                            longInfo(second);
                        }
                    }

                }
                regex = ">[A-z0-9, %]{2,1000}";
                m = Pattern.compile(regex).matcher(first);
                sb.setLength(0);
                while (m.find()) {
                    sb.append(m.group());
                }
                String temp = sb.toString();
                temp = temp.replaceAll(">","");
                temp = temp.replaceAll("T","t");
                firstlist.put("message",temp);
                longInfo(firstlist.get("message"));


                regex = ">[A-z0-9, %]{2,1000}";
                m = Pattern.compile(regex).matcher(second);
                sb.setLength(0);
                while (m.find()) {
                    sb.append(m.group());
                }
                temp = sb.toString();
                temp = temp.replaceAll(">","");
                temp = temp.replaceAll("T","t");
                secondlist.put("message",temp);
                longInfo(secondlist.get("message"));
            }
            else{
                p = Pattern.compile("<b>Fatal error<\\/b>[A-z :()<>/.0-9]*");
                x = 0;
                for( int i = 0; i < lines.length - 1; i++) {
                    Matcher m = p.matcher(lines[i]);
                    if (m.find()) {
                        if (x == 0) {
                            fatal_error = Boolean.TRUE;
                            x += 1;
                            longInfo(fatal_error.toString());
                        }
                        else{
                            longInfo("Extra fatal error data received");
                        }
                    }

                }
                p = Pattern.compile("\\/\\*\\*\\/\\/\\*Error[\\*={'\"#!;}A-z :()<>/.0-9]*");
                //not verified working
                x = 0;
                for( int i = 0; i < lines.length - 1; i++) {
                    Matcher m = p.matcher(lines[i]);
                    if (m.find()) {
                        if (x == 0) {
                            weather_gov_error = Boolean.TRUE;
                            x += 1;
                            longInfo(weather_gov_error.toString());
                        }
                        else{
                            longInfo("Extra weather.gov error data received");
                        }
                    }

                }

            }





        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        if (first != null & second != null){
            Day1a.setText(months[Integer.parseInt(firstlist.get("month")) - 1] + " " + firstlist.get("day") + ", " + firstlist.get("year"));
            if (Integer.parseInt(firstlist.get("chance")) <= 0) {
                Day1b.setText("Low");
            }
            else{
                Day1b.setText(firstlist.get("chance") + "%");
            }
            Day1c.setText(firstlist.get("message") + ".");
            Day2a.setText(months[Integer.parseInt(secondlist.get("month")) - 1] + " " + secondlist.get("day") + ", " + secondlist.get("year"));
            if (Integer.parseInt(secondlist.get("chance")) <= 0) {
                Day2b.setText("Low");
            }
            else{
                Day2b.setText(secondlist.get("chance") + "%");
            }
            Day2c.setText(secondlist.get("message") + ".");
        }
        else {
            Day1a.setText("Error");
            Day1b.setText("Error");
            Day1c.setText("Error");
            Day2a.setText("Error");
            Day2b.setText("Error");
            Day2c.setText("Error");
            if (fatal_error) {
                ERROR_LOG.setVisibility(View.VISIBLE);
                ERROR_LOG.setText("Website: Fatal Error");
            }
            else {
                ERROR_LOG.setVisibility(View.INVISIBLE);
            }
            if (weather_gov_error) {
                ERROR_LOG.setVisibility(View.VISIBLE);
                ERROR_LOG.setText("Website: Weather Error");
            }
            else {
                ERROR_LOG.setVisibility(View.INVISIBLE);
            }
        }

    }
}

}

cell_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="#ffffff"/>
<stroke android:width="1dp"  android:color="#000000"/>

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout       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"
android:fitsSystemWindows="true"
tools:context="com.example.ersch.noschoolcalculator.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@android:drawable/ic_popup_sync"
    app:backgroundTint="@android:color/holo_green_dark"
    app:rippleColor="@android:color/holo_red_dark" />

contnt_main.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.ersch.noschoolcalculator.MainActivity"
tools:showIn="@layout/activity_main">
<TableRow
    android:gravity="center_horizontal">

    <TextView
        android:background="@drawable/cell_shape"
        android:layout_column="1"
        android:text="Date"
        android:gravity="center_horizontal"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:textColor="@android:color/black"
        android:textSize="18sp" />

    <TextView
        android:background="@drawable/cell_shape"
        android:text="Chance"
        android:gravity="center_horizontal"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:textColor="@android:color/black"
        android:textSize="18sp" />

    <TextView
        android:background="@drawable/cell_shape"
        android:text="Message"
        android:gravity="center_horizontal"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:layout_weight="1"
        android:paddingEnd="10dip"
        android:textColor="@android:color/black"
        android:textSize="18sp" />
</TableRow>

<TableRow android:gravity="center_horizontal"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <TextView
        android:background="@drawable/cell_shape"
        android:gravity="center_horizontal"
        android:layout_column="1"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:id="@+id/Day1a"
        android:textSize="18sp"
        android:layout_height="match_parent" />

    <TextView
        android:background="@drawable/cell_shape"
        android:gravity="center_horizontal"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:id="@+id/Day1b"
        android:textSize="18sp"
        android:layout_height="match_parent" />

    <TextView
        android:background="@drawable/cell_shape"
        android:gravity="center_horizontal"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:id="@+id/Day1c"
        android:textSize="12sp"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</TableRow>

<TableRow android:gravity="center_horizontal">

    <TextView
        android:background="@drawable/cell_shape"
        android:layout_column="1"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:gravity="center_horizontal"
        android:id="@+id/Day2a"
        android:textSize="18sp"
        android:layout_height="match_parent" />

    <TextView
        android:background="@drawable/cell_shape"
        android:gravity="center_horizontal"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:id="@+id/Day2b"
        android:textSize="18sp"
        android:layout_height="match_parent" />

    <TextView
        android:background="@drawable/cell_shape"
        android:gravity="center_horizontal"
        android:padding="3dip"
        android:paddingStart="10dip"
        android:paddingEnd="10dip"
        android:id="@+id/Day2c"
        android:textSize="12sp"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</TableRow>

<TextView
    android:background="@drawable/cell_shape"
    android:gravity="center_horizontal"
    android:padding="3dip"
    android:paddingStart="10dip"
    android:paddingEnd="10dip"
    android:id="@+id/ERROR_LOG"
    android:textSize="12sp"
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Start Alarm"
    android:onClick="startAlarm" />

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Cancel Alarm"
    android:onClick="cancelAlarm" />

Android清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ersch.noschoolcalculator">
<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <receiver android:name=".AlarmReceiver"></receiver>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

错误消息

                                --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.ersch.noschoolcalculator, PID: 2203
              java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getVisibility()' on a null object reference
                  at android.widget.LinearLayout.forceUniformHeight(LinearLayout.java:1380)
                  at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1368)
                  at android.widget.TableRow.onMeasure(TableRow.java:114)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                  at android.widget.TableLayout.measureChildBeforeLayout(TableLayout.java:464)
                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                  at android.widget.TableLayout.measureVertical(TableLayout.java:476)
                  at android.widget.TableLayout.onMeasure(TableLayout.java:439)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                  at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:703)
                  at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
                  at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1367)
                  at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:768)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                  at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
                  at android.view.View.measure(View.java:17547)
                  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
                  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                  at android.view.Choreographer.doFrame(Choreographer.java:550)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I/Message::  theChance[20170219] = -1;  //PREDICTION
I/Message:: {day=19, date=20170219, month=02, chance=-1, year=2017}
I/Message:: {day=20, date=20170220, month=02, chance=-1, year=2017}
Application terminated.

1 个答案:

答案 0 :(得分:1)

这只是意味着视图没有膨胀。从本质上讲,您已经设置了一个条件,您可以在调用回调之前依赖于View来获取膨胀(例如在onCreate方法中)。你不能这样做,一般来说,你不能在真实的手机上预测会发生哪种情况。甚至可能发生在同一部手机上,您的代码可以在50%的时间内工作。基本上你需要延迟调用回调,直到创建完所有内容。