如何在按钮单击

时间:2016-11-12 11:09:43

标签: java android android-fragments

我的应用中有一些不同的片段。在我的HelpFragment我有一个Button。我要做的是,当用户按下Button时,我希望将它们导航到ContactFragment

这是我尝试过的代码。这里的代码崩溃了我的应用程序,所以这里有点不对劲。此代码位于我的MainActivity.java

        Button GoToContact=(Button)findViewById(R.id.btnGoToContact);
            GoToContact.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HelpFragment HelpFragment = new HelpFragment();
                    FragmentManager manager1 = getSupportFragmentManager();
                    manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
                            HelpFragment,
                            HelpFragment.getTag()
                    ).commit();
                }
            });

因此,每个Fragment都有一个布局。所以我的fragment_help布局就是按钮所在的位置。所以我想将它们从fragment_help移到fragment_contact

我的代码来自fragment_help.xml(布局)

    <Button
    android:text="Go to contact"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btnGoToContact"
    style="@android:style/Widget.Button"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:onClick="GoToContact"/>

这是我在HelpFragment上的代码

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class HelpFragment extends Fragment {


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_help, container, false);
}

这也是我ContactFragment的样子。这是我创建Fragment时自动生成的代码。

我加载应用程序时出现错误!

--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sveinung.clock, PID: 2304
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sveinung.clock/com.sveinung.clock.MainActivity}: java.lang.NullPointerException: 
Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void 
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.sveinung.clock.MainActivity.onCreate(MainActivity.java:50)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

这是我的全部MainActivity.java

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

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

    final View rootView = inflater.inflate(R.layout.fragment_help,  container, false);
    final Button goToContact = (Button) rootView.findViewById(R.id.btnGoToContact);

    goToContact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HelpFragment HelpFragment = new HelpFragment();
            FragmentManager manager1 = getSupportFragmentManager();
            manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
                    HelpFragment,
                    HelpFragment.getTag()
            ).commit();
        }
    });

    return rootView;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    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.addDrawerListener(toggle);
    toggle.syncState();

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

    ClockFragment clockFragment = new ClockFragment();
    FragmentManager manager = getSupportFragmentManager();
    manager.beginTransaction().replace(R.id.relativelayout_for_fragment,
            clockFragment,
            clockFragment.getTag()
    ).commit();


}

@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.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();

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

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_clock) {
        ClockFragment clockFragment = new ClockFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction()
                .setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
                .replace(R.id.relativelayout_for_fragment,
                clockFragment,
                clockFragment.getTag()
        ).commit();

    } else if (id == R.id.nav_world_clock) {
        Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();

        /*WorldClockFragment worldClockFragment = new WorldClockFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction()
                .setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
                .replace(R.id.relativelayout_for_fragment,
                worldClockFragment,
                worldClockFragment.getTag()
        ).commit();*/

    } else if (id == R.id.nav_timer) {
        Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
    } else if (id == R.id.nav_stopwatch) {
        Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
    } else if (id == R.id.nav_alarm) {
        Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
    } else if (id == R.id.nav_help) {
        //Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();

        HelpFragment HelpFragment = new HelpFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction()
                .setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
                .replace(R.id.relativelayout_for_fragment,
                        HelpFragment,
                        HelpFragment.getTag()
                ).commit();

    } else if (id == R.id.nav_contact) {
        //Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();

        ContactFragment contactFragment = new ContactFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction()
                .setCustomAnimations(R.anim.anim_slide_in_from_left, R.anim.anim_slide_out_from_left)
                .replace(R.id.relativelayout_for_fragment,
                        contactFragment,
                        contactFragment.getTag()
                ).commit();

    } else if (id == R.id.nav_about) {
        Toast.makeText(this, "Coming soon ", Toast.LENGTH_SHORT).show();
    }

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

}

1 个答案:

答案 0 :(得分:0)

这段代码:

    Button GoToContact=(Button)findViewById(R.id.btnGoToContact);
        GoToContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HelpFragment HelpFragment = new HelpFragment();
                FragmentManager manager1 = getSupportFragmentManager();
                manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
                        HelpFragment,
                        HelpFragment.getTag()
                ).commit();
            }
        });

需要在onCreateView()内。您在onCreateView()中夸大了布局,找到任何子View并返回您的充气布局。即。

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

    final View rootView = inflater.inflate(R.layout.fragment_help, container, false);
    final Button goToContact = (Button) rootView.findViewById(R.id.btnGoToContact);

    goToContact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HelpFragment HelpFragment = new HelpFragment();
            FragmentManager manager1 = getSupportFragmentManager();
            manager1.beginTransaction().replace(R.id.relativelayout_for_fragment,
                    HelpFragment,
                    HelpFragment.getTag()
            ).commit();
        }
    });

    return rootView;
}

试一试。