我想在第二个活动中显示暂停按钮

时间:2016-04-04 11:49:51

标签: java android xml nullpointerexception

我的MainActivity java文件

  package com.example.lenovo.infinity.app;
  import android.app.Activity;
  import android.content.Intent;
  import android.graphics.Typeface;
  import android.os.Bundle;
  import android.view.MotionEvent;
  import android.view.View;
  import android.widget.ImageView;
  import android.widget.RelativeLayout;
  import android.widget.TextView;
  import com.google.android.gms.ads.AdRequest;

import com.google.android.gms.ads.AdView;
public class MainActivity extends Activity {

RelativeLayout btn;
ImageView imageView;
TextView textView;

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

     adView = (AdView)findViewById(R.id.adsView);
    //adView.setAdSize(AdSize.SMART_BANNER);
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);

    //set font to text view
    textView = (TextView)findViewById(R.id.start_Text);
    Typeface custom = Typeface.createFromAsset(getAssets(),"fonts/font.ttf");
    textView.setTypeface(custom);

    btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return false;
        }
    });

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent myIntent = new Intent(MainActivity.this, Game.class);
            startActivity(myIntent);
        }
    });
}
}

游戏java文件

   package com.example.lenovo.infinity.app;
   import android.app.Activity;
   import android.os.Bundle;
   import android.util.DisplayMetrics;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.widget.RelativeLayout;
   public class Game extends Activity {

View pauseButton;
RelativeLayout Rel_main_game;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics(dm);

    final int heights = dm.heightPixels;
    final int widths = dm.widthPixels;

    LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext()
            .getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);

    pauseButton = layoutInflater.inflate(R.layout.activity_pause,null,false);
    pauseButton.setX(widths - 250);
    pauseButton.setY(0);

    Rel_main_game.addView(pauseButton);

    pauseButton.getLayoutParams().height = 250;
    pauseButton.getLayoutParams().width = 250;
}
}

在我的项目中,我有三个布局:第一个,布局是主要活动,有开始按钮,第二个布局是游戏面板,其中包含一个暂停按钮,按钮是第三个布局

XML文件是 第一个XML,这个xml有开始按钮

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_activity"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageView"
        android:scaleType="fitXY"
        android:src="@drawable/game_bg"
        android:contentDescription="@string/bg" />

    <RelativeLayout
        android:layout_width="@dimen/layout_width"
        android:layout_height="@dimen/layout_height"
        android:layout_alignParentBottom="true"
        android:layout_centerVertical="true"
        android:layout_marginBottom="@dimen/layout_marginBottom"
        android:layout_marginLeft="@dimen/layout_marginLeft"
        android:layout_weight="1">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/StartBtn"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="0dp"
            android:layout_marginStart="0dp"
            android:src="@drawable/btn"
            android:scaleType="fitXY" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/start_game"
            android:id="@+id/start_Text"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:textSize="@dimen/textSize"
            android:textAppearance="@android:style/TextAppearance.Medium" />

    </RelativeLayout>

    <com.google.android.gms.ads.AdView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/adsView"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-5303974617236905/1000694879" />

</RelativeLayout>

第二个XML,它包含带有暂停按钮的主游戏面板

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rel_main_game"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.lenovo.infinity.app.Game">

</RelativeLayout>

第三种布局是暂停按钮

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/pause"
    tools:context="com.example.lenovo.infinity.app.Pause"
    android:background="#000000">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/pauseImage"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/pause_margin"
        android:scaleType="fitXY"
        android:src="@drawable/btn" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="II"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:textSize="@dimen/pause_text_size"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ffffff" />
</RelativeLayout>

我的清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lenovo.infinity.app">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <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="@android:style/Theme.NoTitleBar.Fullscreen">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
        <activity
            android:name=".Game"
            android:screenOrientation="landscape" >
        </activity>
    </application>

</manifest>

logcat的

&#13;
&#13;
04-04 19:47:25.021 8325-8432/? D/GassUtils: Found app info for package com.example.lenovo.infinity.app:1. Hash: e93251d423a7add58a3428a9e259cdd8b57c335ec3a30cc9897279fdeed6e512
04-04 19:47:25.021 8325-8432/? D/k: Found info for package com.example.lenovo.infinity.app in db.
04-04 19:47:25.235 514-703/? V/ActivityManager: com.example.lenovo.infinity.app/.MainActivity: task=TaskRecord{41c684b8 #132 A com.example.lenovo.infinity.app U 0}
04-04 19:47:25.774 8409-8409/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo.infinity.app/com.example.lenovo.infinity.app.MainActivity}: java.lang.NullPointerException
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
                                                     at android.app.ActivityThread.access$600(ActivityThread.java:156)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
                                                     at android.os.Handler.dispatchMessage(Handler.java:99)
                                                     at android.os.Looper.loop(Looper.java:153)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5297)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:511)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                     at dalvik.system.NativeStart.main(Native Method)
                                                  Caused by: java.lang.NullPointerException
                                                     at com.example.lenovo.infinity.app.MainActivity.onCreate(MainActivity.java:38)
                                                     at android.app.Activity.performCreate(Activity.java:5122)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358) 
                                                     at android.app.ActivityThread.access$600(ActivityThread.java:156) 
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340) 
                                                     at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                     at android.os.Looper.loop(Looper.java:153) 
                                                     at android.app.ActivityThread.main(ActivityThread.java:5297) 
                                                     at java.lang.reflect.Method.invokeNative(Native Method) 
                                                     at java.lang.reflect.Method.invoke(Method.java:511) 
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
                                                     at dalvik.system.NativeStart.main(Native Method) 
04-04 19:47:25.782 514-531/? W/ActivityManager:   Force finishing activity com.example.lenovo.infinity.app/.MainActivity
04-04 19:47:25.789 131-131/? I/BufferQueue: [Starting com.example.lenovo.infinity.app](this:0x41f78008,api:2) new GraphicBuffer needed
04-04 19:47:25.803 131-14023/? I/BufferQueue: [Starting com.example.lenovo.infinity.app](this:0x41f78008,api:2) [queue] fps:0.28, dur:3530.34, max:3530.34, min:3530.34
04-04 19:47:25.820 131-204/? I/SurfaceTexture: [Starting com.example.lenovo.infinity.app](this:0x41f91558,api:2) [void* android::SurfaceTexture::createImage(EGLDisplay, const android::sp<android::GraphicBuffer>&)]
04-04 19:47:25.943 8409-8454/? D/dalvikvm: open_cached_dex_file : /data/data/com.example.lenovo.infinity.app/cache/ads1962259775.jar /data/data/com.example.lenovo.infinity.app/cache/ads1962259775.dex
04-04 19:47:26.024 514-535/? V/WindowManager: Changing focus from null to Window{41cae560 u0 Application Error: com.example.lenovo.infinity.app}
04-04 19:47:26.024 514-534/? I/WindowManager: Gaining focus: Window{41cae560 u0 Application Error: com.example.lenovo.infinity.app}
&#13;
&#13;
&#13;

logcat的

3 个答案:

答案 0 :(得分:0)

您对开始和暂停按钮使用相同的按钮:

<ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/pauseImage"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/pause_margin"
        android:scaleType="fitXY"
        android:src="@drawable/btn" />

将其更改为:

<ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/pauseImage"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/pause_margin"
        android:scaleType="fitXY"
        android:src="@drawable/btn_pause" />

其中btn_pause是暂停图像的来源。

答案 1 :(得分:0)

在第二个xml中,您提到您有暂停按钮,但您发布的代码段仅具有相对布局。如果要在另一个视图的顶部显示按钮,请使用Framelayout。

同样在第三个xml中,您需要更改src以暂停图像引用。目前你指的是同一个btn图像。

答案 2 :(得分:0)

在mainActivity中添加此内容

imageView = (ImageView)findViewById(R.id.StartBtn);
        btn = (RelativeLayout)findViewById(R.id.Start_layout);