应用程序在片段内单击按钮时强制关闭

时间:2017-04-22 20:47:04

标签: android android-fragments

我刚刚开始将我的活动转换为片段,刚刚完成转换活动并发现当我点击该片段中的按钮时应用程序正在强行关闭!

这是我的Activity类:Attendence

package wonderkids.wonderkids;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;



import static wonderkids.wonderkids.R.layout.exam;

public class Attendence extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(exam);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onSupportNavigateUp(){
        finish();
        return true;
    }
    Intent browserIntent;

    public void one(View v) {
        Button clickedButton = (Button) v;
        switch (clickedButton.getId()) {
            case R.id.button:
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;
            case R.id.button2:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button3:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button4:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button5:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button6:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button7:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button8:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button9:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button10:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            /*case R.id.fab:{
                Intent i = new Intent(Exams.this, Home.class);
                startActivity(i);
                break;
            }*/
        }
        startActivity(browserIntent);
    }
}

这是应取代Attendence的片段

Attendance.java

package wonderkids.wonderkids;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import static wonderkids.wonderkids.R.layout.exam;


/**
 * A simple {@link Fragment} subclass.
 */
public class Attendance extends Fragment {


    public Attendance() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.exam, container,false);
    }
    Intent browserIntent;

    public void one(View v) {
        Button clickedButton = (Button) v;
        switch (clickedButton.getId()) {
            case R.id.button:
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;
            case R.id.button2:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button3:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button4:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button5:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button6:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button7:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button8:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button9:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}
            case R.id.button10:{
                browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));
                break;}

        }
        startActivity(browserIntent);
    }
}

这是切换片段的主要类:
检查onNavigationItemSelected ...

package wonderkids.wonderkids;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class Home extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private static final String LOG_TAG =
            Home.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.start);
        Log.d(LOG_TAG,"In Create");
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        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);
        Log.d(LOG_TAG,"In Create");
    }

    public void gall1(View view){
        Intent myIntent = new Intent(view.getContext(), Gallery.class);
        startActivityForResult(myIntent, 0);
    }

    public void hw1(View view){
        Intent myIntent = new Intent(view.getContext(), Hworks.class);
        startActivityForResult(myIntent, 0);
    }
    public void con1(View view){
        Intent myIntent = new Intent(view.getContext(), Contact.class);
        startActivityForResult(myIntent, 0);
    }

    public void res1(View view){
        Intent myIntent = new Intent(view.getContext(), Results.class);
        startActivityForResult(myIntent, 0);
    }

    public void sta1(View view){
        Intent myIntent = new Intent(view.getContext(), Staff.class);
        startActivityForResult(myIntent, 0);
    }

    public void bus1(View view){
        Intent browserIntent=new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.google.com"));
        startActivity(browserIntent);
    }

    public void exa1(View view){
        Intent myIntent = new Intent(view.getContext(), Exams.class);
        startActivityForResult(myIntent, 0);
    }

    public void att1(View view){
        Intent myIntent = new Intent(view.getContext(), Attendence.class);
        startActivityForResult(myIntent, 0);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        else if(id==R.id.action_exit) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Fragment fragment = new Fragment();
        if (id == R.id.nav_home) {
            Intent i = new Intent(Home.this, Home.class);
            startActivity(i);
        } else if (id == R.id.nav_gal1ery) {
            Intent i = new Intent(Home.this, Gallery.class);
            startActivity(i);
        } else if (id == R.id.nav_exams) {
            Intent i = new Intent(Home.this, Exams.class);
            startActivity(i);
        } else if (id == R.id.nav_attendence) {
            fragment = new Attendance();

        } else if (id == R.id.nav_results) {
            Intent i = new Intent(Home.this, Results.class);
            startActivity(i);
        } else if (id == R.id.nav_share) {
            try {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, "Wonder Kids");
                String sAux = "\nTry This\n";
                sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
                i.putExtra(Intent.EXTRA_TEXT, sAux);
                startActivity(Intent.createChooser(i, "choose one"));
            } catch(Exception e) {
                //e.toString();
            }
        } else if (id == R.id.nav_cotact) {
            Intent i = new Intent(Home.this, Contact.class);
            startActivity(i);
        } else if (id == R.id.nav_newsletter) {
            Intent browserIntent=new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.google.com"));
            startActivity(browserIntent);
        }
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;


    }
}

这是Attendance(Fragment)的xml文件,我也用于Attendence(Activity)和许多其他...(从其他Activity访问exam.xml时,按钮工作正常)

exam.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back"
    tools:context="wonderkids.wonderkids.Attendance">
    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="27dp"
        android:layout_marginStart="27dp"
        android:onClick="one"
        android:text="1st class"
        app:layout_constraintBaseline_toBaselineOf="@+id/button2"
        app:layout_constraintLeft_toLeftOf="parent"
        tools:layout_constraintBaseline_creator="1"
        tools:layout_constraintLeft_creator="1" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="26dp"
        android:onClick="one"
        android:text="3rd class"
        app:layout_constraintBaseline_toBaselineOf="@+id/button2"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintBaseline_creator="1"
        tools:layout_constraintRight_creator="1" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="27dp"
        android:onClick="one"
        android:text="4th class"
        app:layout_constraintBaseline_toBaselineOf="@+id/button6"
        app:layout_constraintLeft_toLeftOf="parent"
        tools:layout_constraintBaseline_creator="1"
        tools:layout_constraintLeft_creator="1" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="24dp"
        android:onClick="one"
        android:text="6th class"
        app:layout_constraintBaseline_toBaselineOf="@+id/button6"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintBaseline_creator="1"
        tools:layout_constraintRight_creator="1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="55dp"
        android:onClick="one"
        android:text="2nd class"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:onClick="one"
        android:text="5th class"
        app:layout_constraintLeft_toLeftOf="@+id/button2"
        app:layout_constraintRight_toRightOf="@+id/button2"
        app:layout_constraintTop_toBottomOf="@+id/button2"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/button7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:onClick="one"
        android:text="7th class"
        app:layout_constraintLeft_toLeftOf="@+id/button4"
        app:layout_constraintRight_toRightOf="@+id/button4"
        app:layout_constraintTop_toBottomOf="@+id/button4"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/button8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:onClick="one"
        android:text="8th class"
        app:layout_constraintLeft_toLeftOf="@+id/button6"
        app:layout_constraintRight_toRightOf="@+id/button6"
        app:layout_constraintTop_toBottomOf="@+id/button6"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/button9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:onClick="one"
        android:text="9th class"
        app:layout_constraintLeft_toLeftOf="@+id/button5"
        app:layout_constraintRight_toRightOf="@+id/button5"
        app:layout_constraintTop_toBottomOf="@+id/button5"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/button10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="38dp"
        android:onClick="one"
        android:text="10th class"
        app:layout_constraintLeft_toLeftOf="@+id/button8"
        app:layout_constraintTop_toBottomOf="@+id/button8"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintTop_creator="1" />


    </android.support.constraint.ConstraintLayout>
</FrameLayout>

如果需要,这是空容器:

startac.xml

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



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragment_container"
        android:orientation="vertical">

    </LinearLayout>
</LinearLayout>

这是我的清单文件

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



    <application
        android:allowBackup="true"
        android:icon="@mipmap/spl"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/spl"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">


        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".Home" />

        <activity
            android:name=".Home"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:configChanges="orientation"
            android:screenOrientation="portrait"/>
        <activity android:name=".Exams"
            android:screenOrientation="portrait"/>
        <activity android:name=".Results"
            android:screenOrientation="portrait"/>
        <activity android:name=".Contact"
            android:screenOrientation="portrait"/>
        <activity android:name=".Attendence"
            android:screenOrientation="portrait"/>
        <activity android:name=".Hworks"
            android:screenOrientation="portrait"/>
        <activity android:name=".Staff"
            android:screenOrientation="portrait"/>

        <activity
            android:name=".SplashScreen"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="WonderKids"
            android:theme="@style/FullscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Gallery"
            android:label="@string/title_activity_gallery"
            android:theme="@style/AppTheme.NoActionBar" />
    </application>

</manifest>

这是我的崩溃报告:

04-23 02:46:20.797 15458-15458/wonderkids.wonderkids E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: wonderkids.wonderkids, PID: 15458
                                                                       java.lang.IllegalStateException: Could not find method one(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button8'
                                                                           at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                                                                           at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                           at android.view.View.performClick(View.java:5637)
                                                                           at android.view.View$PerformClick.run(View.java:22433)
                                                                           at android.os.Handler.handleCallback(Handler.java:751)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
04-23 02:46:20.828 534-1480/system_process W/ActivityManager:   Force finishing activity wonderkids.wonderkids/.Home

当我看到

附近的出勤(片段)时
import static wonderkids.wonderkids.R.layout.exam;

one

中的

public void one(View v) {

我得到未使用的import语句,方法一从未使用过!
如果您需要任何额外的代码或者没有理解我的问题,请发表评论!

2 个答案:

答案 0 :(得分:2)

如果您尝试使用XML one(View v),则必须在Home类中实现android:onClick

如果您希望片段处理点击,请使用类似

的内容
public class Attendance extends Fragment implements View.OnClickListener {

    public Attendance() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.exam, container,false);

        // Set click listneer
        rootView.findViewById(R.id.button8).setOnClickListener(Attendance.this);

        return rootView;
    }
    Intent browserIntent;

    @Override
    public void onClick(View v) {
        String url;
        switch (v.getId()) {
            case R.id.button:
                url = "https://www.google.com";
                break;
            case R.id.button2:
                url = "https://www.google.com";
                break;
        }
        browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));

答案 1 :(得分:0)

1。从您的Atandance片段中删除import static wonderkids.wonderkids.R.layout.exam;

2。tools:context="wonderkids.wonderkids.Attendance"

中删除exam.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back">

    .....................
    ...................................
</<FrameLayout

CleanBuildRun您的申请。

希望这会起作用〜