Android:默认选项卡式活动在单击按钮时不会启动

时间:2016-08-31 16:46:51

标签: android android-layout android-fragments

我知道这已被问了很多,已经对这个特定主题进行了搜索。并且所有这些都返回相同的答案,但没有解决我的问题,我有一个在单独的xml上创建的按钮,用作片段。 TabbedActivity只是不会启动,单击按钮时应用程序崩溃,甚至在使用的第一个代码上抛出NPE。只是不知道该怎么做。

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Set HomeFragment as user starts the app.
        if (savedInstanceState == null){
            InitStartFrag();
        }

//-----BUG!-----//
1st:Code Used
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)findViewById(R.id.myButton);
    myButton.setOnClickListener(new View.OnClickListener(){
        @Override
            public void onClick(View v){
                Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
                startActivity(intent);
        }
    });

2nd Code:
public void doThis(View view){
        Intent intent = new Intent(this, TabbedActivity.class);
        MainActivity.this.startActivity(intent);
    }

3rd Code:
public void doThis(View view){
        setContentView(R.layout.activity_tabbed);
    }
//-----Bug Ends-----//


        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }



    private void InitStartFrag() {
        android.app.FragmentManager fragmentManager = getFragmentManager();
        android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        .....
        .....
   }

Log Cat:

Process: com.my_app.app_one, PID: 3799
java.lang.IllegalStateException: Could not find a method doThis(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'myButton'
at android.view.View$1.onClick(View.java:3843)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: doThis [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:864)
at android.view.View$1.onClick(View.java:3836)
at android.view.View.performClick(View.java:4471) 
at android.view.View$PerformClick.run(View.java:18778) 
at android.os.Handler.handleCallback(Handler.java:808) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5324) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 

The Manifest:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".TabbedActivity"
            android:label="@string/title_activity_tabbed"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.my_app.app_one.MainActivity" />
        </activity>
    </application>

</manifest>

XML,用作片段:buttons_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <android.support.percent.PercentRelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!--Upper Buttons-->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:text="Fire"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn1"
            android:textColor="@color/colorBtnText1"
            android:drawableStart="@drawable/fire_icon"
            android:drawablePadding="-62dip"
            android:paddingLeft="30dip"
            android:paddingRight="26dip"
            android:singleLine="true"
            android:gravity="center"
            android:onClick="doThis"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton1"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton"
            android:text="Flood"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn3"
            android:textColor="@color/colorBtnText3"/>

        <!-- Divider -->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton2"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@id/myButton1"
            android:text="Thunder"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn2"
            android:textColor="@color/colorBtnText2"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton4"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_below="@id/myButton2"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@id/myButton1"
            android:text="Civil Defense Operation Center"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn4"
            android:textColor="@color/colorBtnText4"/>

        <!--Lower Buttons-->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton5"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton3"
            android:text="Landslide"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn5"
            android:textColor="@color/colorBtnText5"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton7"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton5"
            android:text="Women and Children Protection Center"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn7"
            android:textColor="@color/colorBtnText7"/>

        <!-- Divider -->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton6"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton4"
            android:layout_toEndOf="@id/myButton3"
            android:text="Storm"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn6"
            android:textColor="@color/colorBtnText6"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton8"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_below="@id/myButton6"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@id/myButton5"
            android:text="Earthquake"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn8"
            android:textColor="@color/colorBtnText8"/>


    </android.support.percent.PercentRelativeLayout>


</LinearLayout>

使用新代码:

private void InitBtnListener(){
        LayoutInflater layoutInflater = this.getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.buttons_layout,null);

        android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)view.findViewById(R.id.myButton);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
                startActivity(intent);
            }
        });
    }

TabbedFragment.java代码

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;


public class TabbedFragment extends Fragment implements OnClickListener {

    View myView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.survival_tips_layout,container,false);
        android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)myView.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);
        return myView;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.myButton:

        //--Missing Code:--// 
        After Btn Click Fire up that TabbedActivity.
        //--Ends--//

        // Can I do intents Here?
        Intent intent = new Intent(MainActivity.this,TabbedActivity.class);
        startActivity(intent);
        break;

        }

    }
}

1 个答案:

答案 0 :(得分:0)

This line needs to be above any findViewById

setContentView(R.layout.activity_main);

If the android:onClick is defined from the XML, you need a public method that accepts a View parameter with that name.

For example, android:onClick="doThis" means you need this method

public void doThis(View view) {
    // TODO: Handle click
}

i have a button created on separate xml, used as a fragment

Then you need to find that button from the Fragment class. You can't find it from the Activity.

For example

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        // Inflate the layout
        View rootView = inflater.inflate(R.layoutbuttons_layout, parentViewGroup, false);

        Button button = (Button) rootView.findViewById(R.id.button);
        // TODO: button.setOnClickListener();

        return rootView;
    }

    // OR... if you have android:onclick="doThis"
    public void doThis(View view) {
        // TODO: Handle click
    }
}