Как вызвать фрагмент из меню
Я очень новичок в разработке Java и Android. Таким образом, даже после прочтения многих учебных пособий (например, это, это), я не могу понять, как вызвать фрагмент из 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>
Теперь, когда я добавляю fragment
с помощью android-studio
, он создал файл 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()
Буду благодарен, если кто-нибудь поможет мне в этом.
2 ответа
Вы используете то же имя для фрагмента 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;
Когда вы вызываете фрагмент, создайте 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);
}
}
Вот полный ответ.
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 вы должны определить контейнер, как я делал в своем коде.