【问题标题】:java.lang.IllegalArgumentException: No view found for id for fragment NewLogFragmentjava.lang.IllegalArgumentException:没有为片段 NewLogFragment 的 id 找到视图
【发布时间】:2015-01-10 03:28:18
【问题描述】:

在我的项目中,我有一个位于MainActivity.java 中的导航抽屉。该抽屉中的每个项目都会启动一个占据整个屏幕空间的不同片段。其中一个片段具有需要启动 Activity 的按钮(此 Activity 扩展 MainActivity.java - 其背后的基本原理是保持导航抽屉可用)。当我按下该片段中的任何按钮以启动另一个活动时,我收到此错误

java.lang.RuntimeException: Unable to start activity ComponentInfo{.AddWorkoutActivity}: java.lang.IllegalArgumentException: 
No view found for id 0x7f0a0041 (id/contentFrame) for fragment NewLogFragment{529f3328 #0 id=0x7f0a0041}

这里,NewLogFragment 是尝试启动新活动的片段。

基本上,我的项目结构是这样的: MainActivity:java -> 包含 NavDrawer 并启动一个片段 -> 该片段然后启动另一个活动,这会导致错误。

这是我的一些代码:

public class MainActivity extends ActionBarActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // rest of the code. Note, DrawerList is the list of items in the drawer.

        DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int editedPosition = position + 1;
                Toast.makeText(MainActivity.this, "You selected item " + editedPosition, Toast.LENGTH_SHORT).show();

                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction ft = fragmentManager.beginTransaction();

                switch(position){
                    case 0:

                        ft.replace(R.id.contentFrame, new NewLogFragment()).commit();

                        break;

}
                mDrawerLayout.closeDrawer(mDrawerList);
            }
        }); // ... rest of the code

activity_main.xml

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/primary"
        app:popupTheme="@style/Theme.AppCompat"
        app:theme="@style/ToolbarTheme" />



    <!-- Main layout -->
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/contentFrame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></FrameLayout>


        <!-- Nav drawer -->
        <ListView
            android:id="@android:id/list"
            android:layout_width="305dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@android:color/white" />
    </android.support.v4.widget.DrawerLayout>    
</LinearLayout>

NewLogFragment.java

public class NewLogFragment extends Fragment {


    private Button bt_button;

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

        View rootView = inflater.inflate(R.layout.newlog_layout, container, false);
        bt_button = (Button) rootView.findViewById(R.id.bt_button);

        bt_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddWorkoutActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
            }
        });

    return rootView;
}

@Override
    public void onDestroyView() {
        super.onDestroyView();
    }

newlog_layout.xml

<RelativeLayout 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"
    android:id="@+id/fragmentOne">

    <LinearLayout
        android:id="@+id/ll_buttons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/bt_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/bt_button" />


    </LinearLayout>

</RelativeLayout>

也许我的项目结构不正确......但我已经在网上查看过,但这应该可以工作。不知道出了什么问题。任何关于构建我的项目的最佳方式的建议都值得赞赏(无论是保持这种方式还是将所有内容都变成片段或活动)。但我想先解决这个问题。

编辑添加 AddWorkoutActivity.java

public class AddWorkoutActivity extends MainActivity implements View.OnClickListener {

    TextView tv_warmupex, tv_mainex, tv_workout_type, tv_cycle, tv_week, tv_one_rm;
    EditText ev_datepicker;
    // more layout stuff

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addworkout_layout);

        dateFormatter = new SimpleDateFormat("MM-dd-yyyy", Locale.US);

        Intent logFragmentIntent = getIntent();

        workout_type = logFragmentIntent.getStringExtra("workout_type");
        setUpLayout(workout_type);
    }

    // and a bunch of helper methods that do all the calculations

   public void completeWorkout(MenuItem item) {
    if (cb_wu_1.isChecked() && cb_wu_2.isChecked() && cb_wu_3.isChecked() &&
            cb_me_1.isChecked() && cb_me_2.isChecked() && cb_me_3.isChecked()) {
        // add workout to database
        HashMap<String, String> queryValuesMap = new HashMap<String, String>();

        queryValuesMap.put("table", MAIN_E);
        queryValuesMap.put(WEEK, String.valueOf(e_info[1])); // get latest cycle/week for this exercise and +1 to add to the table
        queryValuesMap.put(CYCLE, String.valueOf(e_info[0]));
        queryValuesMap.put(WEIGHT, getWeightString());
        queryValuesMap.put(DATE_CREATED, changeDateFormat(ev_datepicker.getText().toString()));
        queryValuesMap.put(NOTES, "notes");
        queryValuesMap.put(MAIN_EXERCISE, workout_type);

        dbTools.insertExercise(queryValuesMap);

        // Update 1RM table  if a new rep max is achieved during current workout
        if (Double.parseDouble(getWeightString())>oneRepMax){

            HashMap<String, String> queryValuesMapOneRM = new HashMap<String, String>();

            queryValuesMapOneRM.put(MAIN_EXERCISE, workout_type); // get latest cycle/week for this exercise and +1 to add to the table
            queryValuesMapOneRM.put(WEIGHT, getWeightString());
            queryValuesMapOneRM.put(DATE_CREATED, changeDateFormat(ev_datepicker.getText().toString()));
            dbTools.updateExerciseRepMax(queryValuesMapOneRM);

        }

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    } else {
        /*if not all buttons are clicked, show a toast
          telling user to click all buttons to complete workout
        */
    }
}

}

【问题讨论】:

  • 检查您在 NewLogFragment 类 Fragment 中的导入应该从 spport.v4 导入
  • 确实...我已经检查了所有的 java 类
  • 您是否在清单中注册了 AddWorkoutActivity。可以发一下 AddWorkoutActivity 类的相关代码吗?
  • @naja:你用ft.add()试过了吗?
  • 如果您发布AddWorkoutActivity活动的代码会很有帮助

标签: android android-activity android-fragments navigation-drawer onitemclicklistener


【解决方案1】:

发生崩溃的原因是,您试图用当前活动中不包含的 id 替换片段。我的建议是更改项目结构,例如,为 NavDrawer 使用一个活动并为每个菜单使用片段。否则会更复杂。请参考以下链接,http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

【讨论】:

  • 好的,但是如果我的菜单片段需要打开另一个屏幕(那不是菜单片段)怎么办。你的建议是让那个屏幕也成为一个片段?所以在我的应用程序中,我将只有一个 MainActivity 和一堆片段?
  • 菜单片段是什么意思?
  • 如果我需要向该非菜单片段发送消息该怎么办?活动很容易。在我的非菜单 AddWorkoutActivity 中,我只是根据意图调用 getStringExtra()。
  • 菜单片段 - 通过从导航抽屉中选择一个项目来打开的片段。很抱歉造成混乱。
  • 那么对于非菜单片段,您可以使用 Activity 类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
相关资源
最近更新 更多