【问题标题】:How to call a fragment from menu如何从菜单中调用片段
【发布时间】:2018-02-09 08:05:14
【问题描述】:

我对 java 和 android 开发非常陌生。所以,即使阅读了很多教程(例如thisthis),我还是不知道如何从bottomnevigationmenu 项目中调用片段。

目前,我有:

MainActivity.java

package com.example.myapplication;

import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private void loadCalFragment() {
        String string1="Hello",string2 = "Hii";

        CalFragment fragment = CalFragment.newInstance(string1,string2);
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_frame, fragment);
        ft.commit();
    }

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {



        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Context context = getApplicationContext();
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    Toast toasth = Toast.makeText(context , R.string.title_home, Toast.LENGTH_LONG);
                    toasth.show();
                    return true;
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
                    toastd.show();
                    loadCalFragment();
                    return true;
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_location);
                    Toast toastn = Toast.makeText(context , R.string.title_location, Toast.LENGTH_LONG);
                    toastn.show();
                    return true;
            }
            return false;
        }
    };

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

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

}

activaty_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.MainActivity">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:text="@string/title_home"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>

现在,当我使用android-studio 添加fragment 时,它已经创建了xml 文件。我的目标是在这个片段中创建一个日期选择器并显示它。但是,我不知道该怎么做。

fragment_cal.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.myapplication.CalFragment">

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

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:calendarViewShown="false"
        android:datePickerMode="spinner" />

</FrameLayout>

以及对应的java文件:

calFragment.java

package com.example.myapplication;

import android.content.Context;
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;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link CalFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link CalFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CalFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CalFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CalFragment newInstance(String param1, String param2) {
        CalFragment fragment = new CalFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

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

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

我的 AndroidManifest.xml 是:

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

当我尝试将 CalFragment() 调用附加到导航菜单时:

case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
                    toastd.show();
                    CalFragment();
                    return true;

给出错误:Error:(32, 21) error: cannot find symbol method CalFragment()

如果有人能帮助我,我将不胜感激。

【问题讨论】:

  • 你遇到了什么问题?
  • 我打算为您提供答案的完整源代码,但后来我发现您没有实现任何显示片段的东西。这不是一个教程网站,首先实现一些东西,然后如果您遇到任何错误,有人会帮助您。
  • @Abhishekkumar:感谢您的回复。我已经更新了这个问题。请看问题的底部。
  • @ZankrutParmar:实际上问题是我做的是至少它可以构建。现在,我已经用导致错误的代码部分修改了问题。
  • 好的,告诉我您要在其中显示片段的容器代码在哪里

标签: java android android-fragments


【解决方案1】:

您对片段 CalFragment() 和方法 CalFragment() 使用相同的名称

改为以下:

case R.id.navigation_dashboard:
                mTextMessage.setText(R.string.title_dashboard);
                Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
                toastd.show();
                loadCalFragment();
                return true;

当你调用fragment时,创建loadCalFragment();方法

在您的 Activity 类中创建如下所示的方法,您没有将两个字符串值传递给您的片段newInstance 使用 CalFragment fragment = CalFragment.newInstance(string1,string2); 传递您的实际数据,我使用了演示数据:

private void loadCalFragment() {
   String string1,string2 = "Hii"

    CalFragment fragment = CalFragment.newInstance(string1,string2);
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, fragment);
    ft.commit();
}

从我的代码(活动)更新您的代码:

     package com.example.myapplication;

import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {



    private TextView mTextMessage;

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

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Context context = getApplicationContext();
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    Toast toasth = Toast.makeText(context , R.string.title_home, Toast.LENGTH_LONG);
                    toasth.show();
                    return true;
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
                    toastd.show();
                    loadCalFragment();
                    return true;
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_location);
                    Toast toastn = Toast.makeText(context , R.string.title_location, Toast.LENGTH_LONG);
                    toastn.show();
                    return true;
            }
            return false;
        }
    };


    private void loadCalFragment() {
        CalFragment fragment = CalFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_frame, fragment);
        ft.commit();
    }

    }

还有 CalFragment 代码在这里:

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


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


    public CalFragment() {
        // 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_cal, container, false);
    }

}

【讨论】:

  • 抱歉,我对 java 很陌生,我收到了这个错误:Error:(22, 43) error: method newInstance in class CalFragment cannot be applied to given types; required: String,String found: no arguments reason: actual and formal argument lists differ in length Error:(24, 24) error: cannot find symbol variable fragment_frame 这是用于 loadCalFragment() 声明的。
  • 您能详细说明一下吗?
  • 请更新完整的活动代码,我明白这个问题@BaRud
  • 用我的代码更新你的活动和片段代码,确保它对你有用@BaRud
  • 欢迎@BaRud,很高兴为您提供帮助
【解决方案2】:

这是完整的答案。

activity_main.xml

<android.support.design.widget.CoordinatorLayout 
    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"
    tools:showIn="@layout/app_tab_bar">

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

app_tab_bar.xml

<android.support.design.widget.CoordinatorLayout             
    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">

    <include layout="@layout/activity_main" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:itemBackground="@android:color/white"
        android:foreground="?attr/selectableItemBackground"
        app:itemIconTint="@color/colorAccent"
        app:itemTextColor="@color/colorAccent"
        app:menu="@menu/navigation" />

</android.support.design.widget.CoordinatorLayout>

MainActivity.java

    protected void onCreate(Bundle savedInstanceState) {
    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    // load the first fragment by default
    loadFragment(new Frag_one());
}

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment;
        switch (item.getItemId()) {
            case R.id.navigation_explore:
                fragment = new Frag_one();
                loadFragment(fragment);
                return true;
            case R.id.navigation_saved:
                fragment = new Frag_two();
                loadFragment(fragment);
                return true;
            case R.id.navigation_inbox:
                fragment = new Frag_three();
                loadFragment(fragment);
                return true;
            case R.id.navigation_profile:
                fragment = new Frag_four();
                loadFragment(fragment);
                return true;
        }
        return false;
    }
};

private void loadFragment(Fragment fragment) {
    // load fragment
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

为了显示片段,您必须在 xml 文件中定义一个容器。 Framelayout 用作片段的占位符。因此,在您的 mainactivity.xml 中,您需要像我在代码中那样定义容器。

【讨论】:

  • 嗨,我收到不兼容类型的错误:错误:(37、32)错误:不兼容的类型:CalFragment 无法转换为片段错误:(58、22)错误:不兼容的类型:CalFragment 不能转换为 Fragment 错误:(63, 87) 错误:不兼容的类型:android.support.v4.app.FragmentTransaction 无法转换为 android.app.FragmentTransaction 可以检查一下吗?
  • 在我的代码中,您只需要替换片段类,只需删除您的 calfragment 方法并使用我的加载片段方法。同样正如@Abhishek kumar 所说,您需要为方法和片段使用不同的名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2015-07-07
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多