错误:java.lang.ClassCastException:android.widget.Button无法强制转换为android.view.ViewGroup

时间:2021-05-12 15:52:02

Can anyone assist me in figuring out the cause for this android.widget.Button cannot be cast to android.view.ViewGroup error? I've spent several hours looking for clues online but none of the issues highlighted by other users has led to a solution for me.

任何人都可以帮助我搞清楚这个android.widget.Button的原因是不是可以强制转换为android.view.ViewGroup错误?我花了几个小时在线寻找线索,但其他用户突出显示的问题都没有为我找到解决方案。

public class LandingPageActivity extends Activity {@
    Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final String packageName = this.getClass().getPackage().getName();
        final Context context = this;

        // ScrollView
        ViewGroup contentView = (ViewGroup) LayoutInflater.from(context)
            .inflate(R.layout.activity_landing_page, null);

        // Layout containing Buttons
        ViewGroup g = (ViewGroup) contentView.getChildAt(0);
        int count = g.getChildCount();

        for (int i = 0; i < count; i++) {
            Button btn = (Button) g.getChildAt(i);
            final String text = btn.getText().toString();
            btn.setOnClickListener(new OnClickListener() {@
                Override
                public void onClick(View v) {
                    try {
                        Class c = Class.forName(packageName + "." + text);
                        startActivity(new Intent(context, c));
                    } catch (ClassNotFoundException e) {
                        Toast.makeText(context, String.valueOf(e), 5000).show();
                    }
                }
            });
        }
        setContentView(contentView);
    }
}

activity_landing_page.xml

activity_landing_page.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Click Button" />

</ScrollView>

Error Log

错误日志

01-22 22:05:45.068: E/AndroidRuntime(29628): FATAL EXCEPTION: main
01-22 22:05:45.068: E/AndroidRuntime(29628): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.clarkben.android.footballinsight/com.clarkben.android.footballinsight.LandingPageActivity}: java.lang.ClassCastException: android.widget.Button cannot be cast to android.view.ViewGroup
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.os.Looper.loop(Looper.java:137)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.ActivityThread.main(ActivityThread.java:5103)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at java.lang.reflect.Method.invokeNative(Native Method)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at java.lang.reflect.Method.invoke(Method.java:525)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at dalvik.system.NativeStart.main(Native Method)
01-22 22:05:45.068: E/AndroidRuntime(29628): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.view.ViewGroup
01-22 22:05:45.068: E/AndroidRuntime(29628):    at com.clarkben.android.footballinsight.LandingPageActivity.onCreate(LandingPageActivity.java:27)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.Activity.performCreate(Activity.java:5133)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-22 22:05:45.068: E/AndroidRuntime(29628):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
01-22 22:05:45.068: E/AndroidRuntime(29628):    ... 11 more

3 个解决方案

#1


2  

instead of using getChildAt() you should be directly addressing your components like this:

而不是使用getChildAt(),你应该直接寻址你的组件,如下所示:

findViewById(R.id.button1)

#2


0  

Try changing your code to:

尝试将代码更改为:

// ScrollView
ViewGroup contentView = (ViewGroup) LayoutInflater.from(context)
    .inflate(R.layout.activity_landing_page, null);

// Layout containing Buttons
int count = contentView.getChildCount();

for (int i = 0; i < count; i++) {
    Button btn = (Button) contentView.getChildAt(i);
    final String text = btn.getText().toString();
    btn.setOnClickListener(new OnClickListener() {@
        Override
        public void onClick(View v) {
            try {
                Class c = Class.forName(packageName + "." + text);
                startActivity(new Intent(context, c));
            } catch (ClassNotFoundException e) {
                Toast.makeText(context, String.valueOf(e), 5000).show();
            }
        }
    });
}
setContentView(contentView);

#3


0  

This is how you are inflating your view, i dont know why you would use Viewgroup instead of the actual class. It also clarifies which object from your Layout you are accessing

这是你如何夸大你的观点,我不知道为什么你会使用Viewgroup而不是实际的类。它还阐明了您正在访问的Layout中的哪个对象

ScrollView  contentView = (ScrollView) LayoutInflater.from(context).inflate(R.layout.activity_landing_page, null);

bseides that, you do know that you can actually just set the xml as contentView? See end of post

bseides,你知道你实际上只能将xml设置为contentView吗?见帖子的结尾

Inline the count, makes the code shorter since it doesnt look like you are using that int again.

内联计数,使代码更短,因为它看起来不像你再次使用那个int。

for (int i = 0; i < contentView.getChildCount(); i++) {
    Button btn = (Button) contentView.getChildAt(i);
    final String text = btn.getText().toString();
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Class c = Class.forName(packageName + "." + text);
                startActivity(new Intent(context, c));
            } catch (ClassNotFoundException e) {
                Toast.makeText(context, String.valueOf(e), 5000).show();
            }
        }
    });
}
setContentView(contentView);

Besides that you could access the Button like this:

除此之外,您可以像这样访问Button:

contentView.findViewById(R.id.button1);

but i assume you are going to add a lot more buttons, even tho i dont think that it will look too good with just a massive amount of buttons.

但我认为你会添加更多的按钮,即使你不认为它只会有大量的按钮看起来太好了。

Another approach

另一种方法

This is doing just the same as your code, but significantly shorter.

这与您的代码完全相同,但明显更短。

setContentView(R.layout.activity_landing_page):

Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
    Override
    public void onClick(View v) {
        try {
            Class c = Class.forName(packageName + "." + text);
            startActivity(new Intent(context, c));
        } catch (ClassNotFoundException e) {
            Toast.makeText(context, String.valueOf(e), 5000).show();
        }
    }
});

#1


2  

instead of using getChildAt() you should be directly addressing your components like this:

而不是使用getChildAt(),你应该直接寻址你的组件,如下所示:

findViewById(R.id.button1)

#2


0  

Try changing your code to:

尝试将代码更改为:

// ScrollView
ViewGroup contentView = (ViewGroup) LayoutInflater.from(context)
    .inflate(R.layout.activity_landing_page, null);

// Layout containing Buttons
int count = contentView.getChildCount();

for (int i = 0; i < count; i++) {
    Button btn = (Button) contentView.getChildAt(i);
    final String text = btn.getText().toString();
    btn.setOnClickListener(new OnClickListener() {@
        Override
        public void onClick(View v) {
            try {
                Class c = Class.forName(packageName + "." + text);
                startActivity(new Intent(context, c));
            } catch (ClassNotFoundException e) {
                Toast.makeText(context, String.valueOf(e), 5000).show();
            }
        }
    });
}
setContentView(contentView);

#3


0  

This is how you are inflating your view, i dont know why you would use Viewgroup instead of the actual class. It also clarifies which object from your Layout you are accessing

这是你如何夸大你的观点,我不知道为什么你会使用Viewgroup而不是实际的类。它还阐明了您正在访问的Layout中的哪个对象

ScrollView  contentView = (ScrollView) LayoutInflater.from(context).inflate(R.layout.activity_landing_page, null);

bseides that, you do know that you can actually just set the xml as contentView? See end of post

bseides,你知道你实际上只能将xml设置为contentView吗?见帖子的结尾

Inline the count, makes the code shorter since it doesnt look like you are using that int again.

内联计数,使代码更短,因为它看起来不像你再次使用那个int。

for (int i = 0; i < contentView.getChildCount(); i++) {
    Button btn = (Button) contentView.getChildAt(i);
    final String text = btn.getText().toString();
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Class c = Class.forName(packageName + "." + text);
                startActivity(new Intent(context, c));
            } catch (ClassNotFoundException e) {
                Toast.makeText(context, String.valueOf(e), 5000).show();
            }
        }
    });
}
setContentView(contentView);

Besides that you could access the Button like this:

除此之外,您可以像这样访问Button:

contentView.findViewById(R.id.button1);

but i assume you are going to add a lot more buttons, even tho i dont think that it will look too good with just a massive amount of buttons.

但我认为你会添加更多的按钮,即使你不认为它只会有大量的按钮看起来太好了。

Another approach

另一种方法

This is doing just the same as your code, but significantly shorter.

这与您的代码完全相同,但明显更短。

setContentView(R.layout.activity_landing_page):

Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
    Override
    public void onClick(View v) {
        try {
            Class c = Class.forName(packageName + "." + text);
            startActivity(new Intent(context, c));
        } catch (ClassNotFoundException e) {
            Toast.makeText(context, String.valueOf(e), 5000).show();
        }
    }
});