当前位置:网站首页>JetPack - - - Navigation
JetPack - - - Navigation
2022-06-13 06:25:00 【m0_ forty-seven million nine hundred and fourteen thousand one 】
1.Navigation The birth of
Activity Nesting multiple Fragment Of UI Architectural patterns are already very common , But yes. Fragment It has been a troublesome thing to manage . We need to pass FragmentManager and FragmentTransaction To manage Fragment Switch between . The switching of pages usually also includes the application Appbar Management of 、Fragment Switching between animations , as well as Fragment Parameter transfer between . Pure code is not particularly friendly to use , also Fragment and Appbar In the process of management and use Appear confused .
So ,Jetpack Provides Navigation Components , For our convenience Manage pages and AppBaro.
2.Navigation The advantages of
1. Visual page navigation map , Be similar to AppleXcode Medium StoryBoard, It is convenient for us to clarify the page relationship .
2. adopt destination and action Complete the navigation between pages .
3. Easy to add page switching animation .
4. Type safe parameter passing between pages .
5. adopt NavigationUl, On the menu 、 Bottom navigation 、 Drawer menu navigation for unified management .
6. Support deep links DeepLinko
3.Navigation The main elements of
NavigationGraph, A new kind of XML Resource file , Contains all the pages of the application , And between pages
Relationship .
NavHostFragment, A special Fragment, You can think of it as something else Fragment The container of ,NavigationGraph Medium Fragment It is through NavHostFragment On display .
NavController, Used to complete... In code NavigationGraph Specific page switching work in .
The relationship between their three responsibilities .
When you want to switch Fragment when , Use NavController object , Tell it you want to go NavigationGraph Which of them? Fragment,NavContr011er Will you want to go Fragment Exhibition NavHostFragment in .
4.Navigation application
First, add dependencies :
implementation 'androidx.navigation:navigation-fragment:2.3.5'
implementation 'androidx.navigation:navigation-ui:2.3.5'And then res Folder Create Navigation Folder , And then create the XML file .

<androidx.constraintlayout.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/my_pager"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>This is MainActivity Of Xml file , adopt XML add to NavHostFragment.
android:nameAttribute containsNavHostThe name of the implemented class .
app:navGraphProperty will beNavHostFragmentAssociated with the navigation map . The navigation map will be hereNavHostFragmentSpecify all destinations that users can navigate to .app:defaultNavHost="true"Properties ensure that yourNavHostFragmentWill intercept the system return button . Please note that , There can only be one defaultNavHost. If the same layout ( for example , Double pane layout ) There are multiple hosts in , Be sure to specify only one defaultNavHost.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// obtain navController
NavController navController = Navigation.findNavController(this, R.id.fragment);
// Set up ActionBar
NavigationUI.setupActionBarWithNavController(this,navController);
}
}<navigation 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/my_pager"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.navigtion.HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home" >
<action
android:id="@+id/action_homeFragment_to_blankFragment"
app:destination="@id/blankFragment" />
<argument
android:name="user_name"
app:argType="string"
android:defaultValue="unknown"
/>
<argument
android:name="age"
app:argType="integer"
android:defaultValue="0"
/>
</fragment>
<fragment
android:id="@+id/blankFragment"
android:name="com.example.navigtion.BlankFragment"
android:label="fragment_blank"
tools:layout="@layout/fragment_blank" >
<action
android:id="@+id/action_blankFragment_to_homeFragment"
app:destination="@id/homeFragment" />
</fragment>
</navigation>This is my_pager, Namely Navigation Navigation files for .
navigation Under the label :
app:startDestination Set the starting point fragment
fragment Under the label :
android:name fragment The location of the file
tools:layout fragment Of Xml file
action Under the label :
app:destination action Destination
argument Under the label :
android:name The attribute name
app:argType Attribute types
android:defaultValue The default value is
public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button = getView().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new HomeFragmentArgs.Builder()
.setUserName(" Xiaohua ")
.setAge(12)
.build()
.toBundle();
// Pass value , It can also be used here or not my_pager The configuration in the file can be used directly Arguments Transfer values and then take values like this Bundle bundle = new Bundle();
// bundle.putString("user_name"," Xiaohua ");
// bundle.putInt("age",12);
// navController.navigate(R.id.action_homeFragment_to_blankFragment,bundle);
NavController navController = Navigation.findNavController(v);
// Execute this action Event and pass value
navController.navigate(R.id.action_homeFragment_to_blankFragment,bundle);
}
});
}
}public class BlankFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Value , It can also be used here or not my_pager The configuration in the file can be used directly Arguments Transfer values and then take values like this age = getArguments().getInt("age");
HomeFragmentArgs homeFragmentArgs = HomeFragmentArgs.fromBundle(getArguments());
String userName = homeFragmentArgs.getUserName();
int age = homeFragmentArgs.getAge();
Log.i("ning",userName+" "+age);
Button button = getView().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(v);
// Execute this action event
navController.navigate(R.id.action_blankFragment_to_homeFragment);
}
});
}
}Effect demonstration :

5.Navigation stay app Bar And menu Application in
<navigation 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/my_graph"
app:startDestination="@id/mainFragment"
>
<fragment
android:id="@+id/mainFragment"
android:name="com.example.navigtion2.MainFragment"
android:label="fragment_main"
tools:layout="@layout/fragment_main" />
<fragment
android:id="@+id/settingsFragment"
android:name="com.example.navigtion2.SettingsFragment"
android:label="fragment_settings"
tools:layout="@layout/fragment_settings"
>
</fragment>
</navigation>Navigation Navigation Xml file .
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- there id Want to be with navigation The target in the file fragment id Agreement -->
<item android:id="@+id/settingsFragment" android:title=" This interface "/>
</menu>Upper right corner menu The configuration file .
public class MainActivity extends AppCompatActivity {
private NavController navController;
private AppBarConfiguration appBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navController = Navigation.findNavController(this, R.id.fragment);
// establish appBar
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
// binding
NavigationUI.setupActionBarWithNavController(this,navController, appBarConfiguration);
}
// Set the menu in the upper right corner
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_setting,menu);
return true;
}
@Override// Click on the monitor menu
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
return NavigationUI.onNavDestinationSelected(item,navController) || super.onOptionsItemSelected(item);
}
@Override // Back to previous page
public boolean onSupportNavigateUp() {
return NavigationUI.navigateUp(navController,appBarConfiguration)||super.onSupportNavigateUp();
}
}
The main methods focus on activity in .
public class MainFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
}public class SettingsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_settings, container, false);
}
}Effect demonstration :

5.Pendinglntent( Notice jump ) The way
public class MainFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button = getView().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setNotification();
}
});
}
private void setNotification() {
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
NotificationChannel myChannel = new NotificationChannel(getActivity().getPackageName(), "MyChannel", NotificationManager.IMPORTANCE_DEFAULT);
myChannel.setDescription("my");
NotificationManager systemService = getActivity().getSystemService(NotificationManager.class);
systemService.createNotificationChannel(myChannel);
}
Notification build = new NotificationCompat.Builder(getActivity(), getActivity().getPackageName())
.setContentTitle("Deep Link")
.setContentText(" Let me try ")
.setSmallIcon(R.drawable.ic_launcher_background)
.setDefaults(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(getPendingIntent())
.build();
NotificationManagerCompat from = NotificationManagerCompat.from(getActivity());
from.notify(1,build);
}
private PendingIntent getPendingIntent() {
// Pass value
Bundle bundle = new Bundle();
bundle.putString("name","xiaohua");
return Navigation.findNavController(getActivity(),R.id.button)
.createDeepLink()
.setGraph(R.navigation.my_graph)
.setDestination(R.id.settingsFragment)
.setArguments(bundle)
.createPendingIntent();
}
}Effect demonstration :

6.URI Jump
<fragment
android:id="@+id/settingsFragment"
android:name="com.example.navigtion2.SettingsFragment"
android:label="fragment_settings"
tools:layout="@layout/fragment_settings"
>
<deepLink app:uri="www.xiaohua.com/{param}"/>
</fragment>adopt deepLink Label configuration URI.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<nav-graph android:value="@navigation/my_graph"/>
</activity>Configure the navigation map file in the manifest file .
边栏推荐
- 自定义View —— 可伸展的CollapsExpendView
- PHP redis makes high burst spike
- MFS explanation (VI) -- MFS chunk server installation and configuration
- 线程池学习
- Analysis of synchronized
- Notifyitemchanged flash back
- JS to realize bidirectional data binding
- Uniapp mobile terminal uses canvas to draw background convex arc
- Uni app upload file
- ADB shell content command debug database
猜你喜欢

二分查找

Explication détaillée du triangle Yang hui

MFS details (VII) -- MFS client and web monitoring installation configuration

端午安康,使用祝福话语生成词云吧

MFS详解(六)——MFS Chunk Server服务器安装与配置

推荐扩容工具,彻底解决C盘及其它磁盘空间不够的难题

微信小程序:基础复习

JS to realize bidirectional data binding

华为开发者认证与DevEco Studio编译器下载

Dart class inherits and implements mixed operators
随机推荐
You should consider upgrading via
Recent problems
自定义View —— 可伸展的CollapsExpendView
Vector control of Brushless DC motor (4): sensorless control based on sliding mode observer
ADB shell CMD overlay debugging command facilitates viewing system framework character resource values
Relationship between fragment lifecycle and activity
SSM integration
js将文本转成语言播放
The boys x pubgmobile linkage is coming! Check out the latest game posters
Echart histogram: echart implements stacked histogram
IOError(Errors.E050.format(name=name))
Rk3399 hid gadget configuration
BlockingQueue源码
Fragment lifecycle
1+1 > 2, share creators can help you achieve
App performance test: (II) CPU
RFID process management solution for electroplating fixture
Echart柱状图:堆叠柱状图显示value
HBuilderX:HBuilderX安装以及其常用插件安装
微信小程序:基础复习