【问题标题】:Opening a fragment with a button使用按钮打开片段
【发布时间】:2014-10-15 12:30:01
【问题描述】:

我需要一些帮助。在过去的 4 个小时里,我进行了一些广泛的搜索,但我不确定是因为我的代码中有错误,还是因为我没有正确地做某事。 基本上,这就是正在发生的事情。我有我的主要活动“主页”,它打开到带有导航抽屉的第二个活动。我假设导航抽屉也是一个“活动”。我正在尝试使用按钮打开该活动中的片段,但我不断收到致命异常:

10-14 21:36:54.469      799-799/com.example.workstation.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workstation.app/com.example.workstation.app.navigation_drawer}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.workstation.app.navigationdrawer.onCreate(navigationdrawer.java:57)

这是我正在使用的代码,这个是用于 navigation_drawer 活动的(我相信):

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.workstation.app.navigation_drawer_activity$PlaceholderFragment">

    <TextView
        android:id="@+id/cctr_ct_home"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cctr_ct"
        android:textSize="40sp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cctr_search"
        android:drawableTop="@drawable/search"
        android:layout_below="@+id/cctr_ct_home"
        android:layout_alignLeft="@+id/cctr_ct_home"
        android:layout_alignStart="@+id/cctr_ct_home"
        android:layout_marginTop="95dp"
        android:text="Search"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cctr_favorites"
        android:drawableTop="@drawable/favorites"
        android:layout_alignTop="@+id/cctr_search"
        android:layout_alignRight="@+id/cctr_ct_home"
        android:layout_alignEnd="@+id/cctr_ct_home"
        android:text="Favorite"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cctr_recent"
        android:drawableTop="@drawable/recent"
        android:layout_below="@+id/cctr_search"
        android:layout_alignLeft="@+id/cctr_search"
        android:layout_alignStart="@+id/cctr_search"
        android:layout_marginTop="37dp"
        android:text="Recent"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cctr_contactus"
        android:drawableTop="@drawable/email"
        android:layout_alignTop="@+id/cctr_recent"
        android:layout_alignLeft="@+id/cctr_favorites"
        android:layout_alignStart="@+id/cctr_favorites"
        android:text="Contact Us" />

    <fragment android:name="com.example.workstation.cctrmobileapp.cctrct_search"
        android:id="@+id/cctr_ct_search"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="match_parent" />

</RelativeLayout>

现在,导航抽屉工作正常,它从我遇到问题的按钮打开片段。我得到上面的错误。这是导航抽屉附带的活动的java代码:

package com.example.workstation.cctrmobileapp;

import android.app.Activity;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;


public class cctr_clinical_trials extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, cctrct_search.OnFragmentInteractionListener {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    Button cctrct_searchButton;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        cctrct_searchButton = (Button)findViewById(R.id.cctr_search);

        cctrct_searchButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                cctrct_search newFragment = new cctrct_search();
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                transaction.replace(R.id.container, newFragment);
                transaction.addToBackStack(null);

                transaction.commit();

            }
        });

/*        cctrct_searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                FragmentManager searchFragment = getSupportFragmentManager();

                searchFragment.beginTransaction()

                        .replace(R.id.container, cctrct_search.newInstance("test1", "test2"))

                        .commit();
            }

        });*/


    }

为了它,这是我按下按钮后想要显示的片段的 xml:

<FrameLayout 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"
    tools:context="com.example.workstation.cctrmobileapp.cctrct_search">

    <!-- TODO: Update blank fragment layout -->

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:id="@+id/cctrct_search_submit"
        android:layout_below="@+id/cctrct_p1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="65dp"
        android:layout_gravity="center_horizontal|bottom" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Only the submit button works"
        android:id="@+id/cctr_search_logo"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="43dp"
        android:layout_gravity="center_horizontal|top" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phase III"
        android:id="@+id/cctrct_p3"
        android:layout_toEndOf="@+id/cctrct_search_dsite"
        android:layout_below="@+id/cctrct_search_pnum"
        android:layout_toRightOf="@+id/cctrct_search_dsite"
        android:layout_marginTop="28dp"
        android:layout_gravity="center" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phase II"
        android:id="@+id/cctrct_p2"
        android:layout_toEndOf="@+id/cctrct_p1"
        android:layout_alignTop="@+id/cctrct_p3"
        android:layout_alignLeft="@+id/cctrct_search_keyword"
        android:layout_alignStart="@+id/cctrct_search_keyword"
        android:layout_alignRight="@+id/cctrct_search_dsite"
        android:layout_alignEnd="@+id/cctrct_search_dsite"
        android:layout_gravity="center" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phase I"
        android:id="@+id/cctrct_p1"
        android:layout_toStartOf="@+id/cctrct_search_pnum"
        android:layout_alignTop="@+id/cctrct_p2"
        android:layout_toLeftOf="@+id/cctrct_search_pnum"
        android:layout_gravity="center" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Keyword"
        android:id="@+id/cctrct_search_keyword"
        android:layout_below="@+id/cctrct_search_dsite"
        android:layout_alignRight="@+id/cctrct_search_submit"
        android:layout_alignEnd="@+id/cctrct_search_submit"
        android:layout_marginTop="26dp"
        android:layout_gravity="left|center_vertical" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Disease Site"
        android:id="@+id/cctrct_search_dsite"
        android:layout_below="@+id/cctr_search_logo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:layout_gravity="right|center_vertical" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Protocol Number"
        android:id="@+id/cctrct_search_pnum"
        android:layout_below="@+id/cctrct_search_keyword"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:layout_gravity="left|center_vertical" />

</RelativeLayout>

</FrameLayout>

我只是想我会添加我班级的其余代码:

 @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();

        switch (position) {
            case 0: fragmentManager.beginTransaction()
                    .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                    .commit(); break;
            case 1: fragmentManager.beginTransaction()
                    .replace(R.id.container, cctrct_search.newInstance("test1", "test2"))
                    .commit(); break;
            case 2: fragmentManager.beginTransaction()
                    .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                    .commit(); break;
            case 3: fragmentManager.beginTransaction()
                    .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                    .commit(); break;
        }

    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.cctr_ct_home);
                break;
            case 2:
                mTitle = getString(R.string.cctr_ct_search);
                break;
            case 3:
                mTitle = getString(R.string.cctr_ct_saved);
                break;
            case 4:
                mTitle = getString(R.string.cctr_ct_recent);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.cctr_clinical_trials, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @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);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

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

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((cctr_clinical_trials) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }



    }

}

【问题讨论】:

标签: android android-fragments


【解决方案1】:

看起来cctrct_searchButtonnull,这意味着它在视图找不到ID 为 cctr_search 的按钮是否存在于 activity_cctr_clinical_trials layout xml 文件中

【讨论】:

  • activity_cctr_clinical_trials.xml 仅包含导航抽屉所需的项目。我需要添加一个带有“id =”cctr_search“”的新片段吗?我是否可能将我的片段放在错误的 xml 中?我在 fragment_cctr_clinical_trials.xml 文件中有它
  • 您的 cctr_clinical_trials 夸大了 activity_cctr_clinical_trials。这意味着它只能访问该布局上的视图。从技术上讲,您可以访问片段上的按钮,但只能在添加片段之后。并且片段不会立即添加(除非您调用 executePendingTransactions)。所以问题是,您要按下的这些按钮在哪里?
  • sphanley,我不确定你在和谁说话,但你的评论很没有效率
  • 如果所有这些按钮都放在activity_cctr_clinical_trials.xml 上,这些按钮都放在fragment_cctr_clinical_trials.xml 下吗?
  • 我认为根据您的设置方式,您应该在 Fragments onCreateView 方法中访问和添加按钮侦听器。不是 Activity 的 onCreate
【解决方案2】:

对于未来的用户,Spidy 先生 100% 正确,onClickListener 应该在 onCreateView 而不是 onCreate 部分:

public PlaceholderFragment() {
        }

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


            Button cctrct_searchButton;

            cctrct_searchButton = (Button)rootView.findViewById(R.id.cctr_search);

            cctrct_searchButton.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Fragment newFragment = new cctrct_search();
                    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();

                    transaction.replace(R.id.container, newFragment);
                    transaction.addToBackStack(null);

                    transaction.commit();
                }
            });

            return rootView;

        }

再次感谢先生。蜘蛛侠

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2015-09-05
    • 2015-12-18
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多