java - Android Studio : App doesn't start with implemented Anonymous Java Class

标签 java android xml actionlistener

我发现了错误消息

"5-14 12:39:13.104 2518-2518/com.example.fdai3744.neueleereapp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.fdai3744.neueleereapp, PID: 2518 java.lang.RuntimeException: Unable to instantiate activity ..."

这是我的 Java 代码

package com.example.fdai3744.neueleereapp;

import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


    public class MainActivity extends AppCompatActivity {

        public Button button_1 = (Button) findViewById(R.id.button1); //Button
        public TextView text1 = (TextView)findViewById(R.id.text1); // Textview

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

            button_1.setOnClickListener(new View.OnClickListener() { // Here I add the ActionListener for my button

                @Override
                public void onClick(View v) {
                    text1.setText("Button 1 wurde geklickt!");
                }
            });
        }

    }

如果我启动我的应用程序,模拟器会抛出错误消息“应用程序已停止”。我应该如何防止这个错误?

最佳答案

嗯,您的 View 层次结构需要处于 Activity 状态,然后才能从中检索各个 View,并且 setContentView() 方法将其激活(或实例化)。

如何?

setContentView(View) is a method exclusively available for Activity. Internally it calls the setContentView(View) of Window. This method sets the activity content to an explicit view. This view is placed directly into the activity's view hierarchy. Calling this function "locks in" various characteristics of the window that can not, from this point forward, be changed. Hence it is called only once.

因此,不要将 View 初始化为实例变量,而是在 setContentView() 之后在 onCreate() 中实例化它们。

另请阅读:Android: setContentView and LayoutInflater

关于java - Android Studio : App doesn't start with implemented Anonymous Java Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43964075/

相关文章:

Java Matcher.replaceAll() 也匹配 group(0) 元素

android - 如何在android gridview上进行 ImageView 拖放

jquery - 处理 XML/HTML/JQuery 中的换行符

c# - 在 C# 中解析 dblp.xml 文件时出错

java - 从字符串数组中获取特定项目

java - 如何确定变量是否有作用域和生存期?

java.lang.IllegalArgumentException : Failed to find configured root that contains/storage/emulated/0/

java - 通过访问方法引用属性还是直接在父类(super class)中引用属性?

Android - 将图像垂直发送到服务器时,尽管移动设备中的预览看起来不错,但它们会旋转

java - 如何在使用音乐服务时停止后台音乐