Android编程:控制器类

时间:2017-03-31 18:26:07

标签: android xml eclipse model-view-controller onclicklistener

我有一个活动和一个按钮,点击我要打开另一个活动。我想在我的控制器类中执行按钮单击事件,所以我使用

  

在我的MainActivity.java中

MainController mainController = new MainController(btn_secondpage);
btn_secondpage.setOnClickListener(mainController);

在MainController类中我使用了这些方法 -

  

在MainController类中..

public MainController(Button btn_secondpage) {

    this.btn_secondpage=btn_secondpage;

    }

@Override
public void onClick(View v) {
    Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
    startActivity(intent);

}

但每当我点击按钮时,会打开一个对话框,显示我的应用已停止工作... 我正在使用eclipse mars2 我提供了所有的类,xml,manifest.xml

  
      
  1. activity_main.xml中
  2.   
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_id"
    style="@style/AppTheme"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="false"
    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.testandroidproject.view.MainActivity" >

    <Button
        android:id="@+id/btn_secondpage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Second page" />

</RelativeLayout>
  
      
  1. activity_second.xml
  2.   
<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: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.testandroidproject.view.SecondActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Welcome to second page" />

</RelativeLayout>
  
      
  1. MainActivity.java
  2.   
package com.testandroidproject.view;

import com.example.testandroidproject.R;
import com.testandroidproject.controller.MainController;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    public Button btn_secondpage;
    public static final String TAG = "abcd";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(TAG, "inside oncreate");             // printing (1st)
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        MainController mainController = new MainController(btn_secondpage);
        btn_secondpage.setOnClickListener(mainController);

        //      onButtonClick();  // this is working properly
    }

    ////////////// this method is working properly.......
    public void onButtonClick(){
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        btn_secondpage.setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");   
                        startActivity(intent);

                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //  Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
  
      
  1. SecondActivity.java
  2.   
package com.testandroidproject.view;

import com.example.testandroidproject.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class SecondActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    //  Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, menu);
        return true;
    }

    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
  
      
  1. MainController.java
  2.   
package com.testandroidproject.controller;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainController extends Activity implements OnClickListener {
    Button btn_secondpage;
    public static final String TAG = "abcd";

    public MainController(Button btn_secondpage) {
        this.btn_secondpage=btn_secondpage;
        Log.i(TAG, "inside mainController constructor"); // printing (2nd)
    }

    @Override
    public void onClick(View v) {
        Log.i(TAG, "inside public void onClick before intent");                     // printing(3rd)
        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
        Log.i(TAG, "inside public void onClick after intent");                      // printing(4th)
        startActivity(intent);
        Log.i(TAG, "inside public void onClick after startActivity");               //  NOT printing

    }

}
  
      
  1. 的AndroidManifest.xml
  2.   
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testandroidproject"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="21"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.testandroidproject.view.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.testandroidproject.view.SecondActivity"
            android:label="@string/title_activity_second" >
            <intent-filter>
                <action android:name="com.testandroidproject.view.SecondActivity" />    

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

</manifest>
  
      
  1. logcat的
  2.   
04-01 00:10:38.344: I/abcd(1764): inside oncreate
04-01 00:10:38.345: I/abcd(1764): inside mainController constructor
04-01 00:10:38.370: D/OpenGLRenderer(1764): Render dirty regions requested:     true
04-01 00:10:38.374: D/(1764): HostConnection::get() New Host Connection   established 0xa5f43380, tid 1764
04-01 00:10:38.375: D/Atlas(1764): Validating map...
04-01 00:10:38.399: D/(1764): HostConnection::get() New Host Connection established 0xad480dc0, tid 1780
04-01 00:10:38.401: I/OpenGLRenderer(1764): Initialized EGL, version 1.4
04-01 00:10:38.446: D/OpenGLRenderer(1764): Enabling debug mode 0
04-01 00:10:38.546: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:10:38.546: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:51.749: I/abcd(1764): inside oncreate
04-01 00:11:51.754: I/abcd(1764): inside mainController constructor
04-01 00:11:51.896: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:11:51.896: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:55.658: I/abcd(1764): inside public void onClick before intent
04-01 00:11:55.658: I/abcd(1764): inside public void onClick after intent
04-01 00:11:55.658: D/AndroidRuntime(1764): Shutting down VM
04-01 00:11:55.658: D/AndroidRuntime(1764): --------- beginning of crash
04-01 00:11:55.658: E/AndroidRuntime(1764): FATAL EXCEPTION: main
04-01 00:11:55.658: E/AndroidRuntime(1764): Process:   com.example.testandroidproject, PID: 1764
04-01 00:11:55.658: E/AndroidRuntime(1764): java.lang.NullPointerException:   Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
04-01 00:11:55.658: E/AndroidRuntime(1764):     at   android.app.Activity.startActivityForResult(Activity.java:3736)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android. app.Activity.startActivityForResult(Activity.java:3697)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:4007)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:3975)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.testandroidproject.controller.MainController.onClick(MainController.java:24)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View.performClick(View.java:4756)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View$PerformClick.run(View.java:19749)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.handleCallback(Handler.java:739)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Looper.loop(Looper.java:135)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.ActivityThread.main(ActivityThread.java:5221)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Native Method)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Method.java:372)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.and  roid.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-01 00:11:55.857: I/art(1764): Background sticky concurrent mark sweep GC freed 2383(175KB) AllocSpace objects, 1(81KB) LOS objects, 29% free,    794KB/1135KB, paused 1.621ms total 150.498ms
04-01 00:12:09.406: I/Process(1764): Sending signal. PID: 1764 SIG: 9

enter image description here

1 个答案:

答案 0 :(得分:0)

MainController onClick()课程中

在创建Intent对象时出错,请更改此Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class);

确保您的MainController不是Activity的子类,这会导致错误。因为现在您的活动不是Context的子类,所以无法调用startActivity()。要从传递的按钮

启动活动,请使用上下文
public class MainController implements OnClickListener{
    //............
@Override
public void onClick(View v) {
    Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class);
    btn_secondpage.getContext().startActivity(intent);
}