android - 如何实现带有选项卡 Activity 的按钮

标签 android android-intent

我有一个选项卡 Activity ,然后在其中一个 Activity 中我想放置一个按钮以进行不同的 Activity 。然而,当我对按钮进行编码时(没有错误)但是当启动应用程序时它崩溃并显示错误代码:

11-14 12:50:43.783: E/AndroidRuntime(10933): java.lang.RuntimeException: 无法启动 Activity ComponentInfo{com.dist.distguide/com.dist.distguide.MainActivity}: java .lang.NullPointerException

但是,当我删除编码按钮时,应用程序可以正常启动。

这是我的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/logo1">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" >

        <Button
            android:id="@+id/Distancecalc"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Distance Calculator" />

        <Button
            android:id="@+id/Distance"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Distance Calculator" />

    </FrameLayout>

  </LinearLayout>
 </TabHost>

然后是我的Java:

Intent intentHome = new Intent().setClass(this, HomeActivity.class);
    TabSpec tabSpecHome = tabHost
        .newTabSpec("Home")
        .setIndicator("", ressources.getDrawable(R.drawable.icon_home_config))
        .setContent(intentHome);
    Button add = (Button)findViewById(R.id.Distance1);
    add.bringToFront(); 
    add.setOnClickListener(new View.OnClickListener()
    {
    public void onClick(View v)
    {
         Intent myIntent = new Intent(MainActivity.this,DistanceCalc.class);
            startActivity(myIntent);  
         }
    });

我在这里做错了什么? 请帮忙! 谢谢

最佳答案

改变

Button add = (Button)findViewById(R.id.Distance1);

Button add = (Button)findViewById(R.id.Distancecalc);

您的按钮 ID 是 Distancecalc。并且您正在尝试使用 Distance1 对其进行初始化。

关于android - 如何实现带有选项卡 Activity 的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26928447/

相关文章:

android - 如何让按住按钮启动定时器?

java - 如何在 Android 应用程序中存储用于多个 Activity 的位图

android - 将本地文件附加到电子邮件

android - 如何将多个数据从 fragment 传递到 Activity

android - 在 Android 中执行网络操作的最佳实践是什么?

java - 如何更改我的 fragment 中的文件 XML 属性

java - 如果 Android 终止了我的应用程序并且我从设置中强制关闭,我会收到 GCM 消息吗?

java - 错误 java.lang.RuntimeException : Unable to start activity

android - 使用 Android 导航组件的深层链接打开不正确的屏幕

android - 检测 USB 设备何时在 Android 上分离