Android learning (simple use Bottom Navigation Activity to achieve the bottom navigation bar)

When we actually write programs, we don't have to start from scratch for every activity. Making good use of the templates that come with the system can often get twice the result with half the effort. Let's take a look at how to use Bottom Navigation Activity to complete the simple bottom navigation bar function. Let's take a look at the renderings first:
Insert picture description here
create activity
first in the creation of the panel, we select Insert picture description here
and then next, finish is OK. After the creation is successful, let's run it and find that Insert picture description here
the function of the bottom navigation bar has been basically realized! But it's not over yet-we still need to modify and customize the navigation bar to meet our own needs.
Customize the bottom navigation The bottom navigation
now has only three options, and the icon text is fixed to me. So what should we do if we want to add navigation or change the icon text? First we open the activity_main.xml file and found such a piece of code

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

The last line is used to describe the bottom navigation. It specifies the bottom_nav_menu file under the menu folder. Find it and take a look

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

    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_dashboard"
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="@string/title_dashboard" />

    <item
        android:id="@+id/navigation_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_notifications" />

</menu>

These three items correspond to the three icons you see. Add a line below

<item android:id="@+id/test"     
    android:title="test"
    android:icon="@drawable/compass"/>  

The title attribute is the text that appears below after clicking, and the icon attribute is the icon, which is the download address .
Let's look at the fourth icon (up to 5). So how to change the page after clicking?
Custom switch page
Here we use fragment to switch page.
First change the textview of the activity_main.xml file to

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">

</FrameLayout>

Then create two new layout files under the layout folder (if you want 4 navigations, then create 4 new files, here only create two for testing) layout files
Insert picture description here
and add your own layouts in them.
Then open the java file of mainactivity

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

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                
                return true;
            case R.id.navigation_dashboard:
                
                return true;
            case R.id.navigation_notifications:
                
                return true;
        }
        return false;
    }
};

This piece of code is the listener for the bottom navigation switch (I deleted the textview). Let’s add our own navigation

case R.id.test:

    return true;

Then create two new java files (corresponding to two layouts, here is one as an example)Insert picture description here

public class content1 extends Fragment {		//继承fragment

	//创建视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate( R.layout.layout_1, container, false );  //要加载的layout文件
    }		

}

Next is to modify the mainactivity, I directly posted the code

public class MainActivity extends AppCompatActivity {

    private FragmentTransaction transaction;
    private FragmentManager fragmentManager;

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

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            fragmentManager = getSupportFragmentManager();  //使用fragmentmanager和transaction来实现切换效果
            transaction = fragmentManager.beginTransaction();
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    transaction.replace(R.id.content,new content1());  //对应的java class
                    transaction.commit();  //一定不要忘记commit,否则不会显示
                    return true;
                case R.id.navigation_dashboard:

                    return true;
                case R.id.navigation_notifications:

                    return true;
                case R.id.test:
                    //一样的
                    transaction.replace(R.id.content,new content2());
                    transaction.commit();
                    return true;
            }
            return false;
        }
    };

    // 设置默认进来是tab 显示的页面
    private void setDefaultFragment(){
        fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.content,new content1());
        transaction.commit();
    }

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

        setDefaultFragment();  //上面写的那个函数

        BottomNavigationView navView = findViewById( R.id.nav_view );

        navView.setOnNavigationItemSelectedListener( mOnNavigationItemSelectedListener );
    }

}

It's over here! Of course, this is just the simplest to use. If you want to achieve more complex functions, you have to study it yourself!

Update

The template given in the latest version of Android Studio (3.5) is not the same as the previous one, so update the article.
Let's take a look at the effect first, a button and a textview, click the button to display the current time:
Insert picture description here
file structure
There was only one java file after the previous version was created, and now there are multiple files:

Insert picture description here
The three folders dashboard, home, notifications correspond to the three navigation bars at the bottom. There are two files under each folder, one is the fragment used to carry the control, and the other is the corresponding viewModel. The viewModel is the vm under the mvvm framework. You can also study about the mvvm framework. Here I will just briefly talk about HomeFragment and HomeViewModel in the example.
First of all, these two files are ordinary java classes. Fragment is used to display the UI interface, while the viewmodel provides data for the UI interface. Each control in the view has a corresponding data object in the viewmodel. If you want to update the UI interface on the view, you only need to update it in the viewmodel. The corresponding object can be.
Insert picture description here
Customizing the navigation bar The customization of the navigation bar
is roughly the same as before. If we want to add a new navigation page of our own, we can do this: bottom_nav_menu.xml under the menu folder corresponds to the navigation icon at the bottom, and add our own item.

<item
    android:id="@+id/navigation_my"
    android:icon="@drawable/ic_notifications_black_24dp"
    android:title="MyNavigation" />

Then create a new folder under the ui folder named myNavagation, in which new a fragment->fragment with viewmodel,
Insert picture description here
and modify the mainActivity part of the code as follows:

BottomNavigationView navView = findViewById( R.id.nav_view );
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
        R.id.navigation_my, R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications )
        .build();

Add the code in mobile_navigation.xml under the navigation folder:

<fragment
    android:id="@+id/navigation_my"
    android:name="com.angel.hand.myapplication.ui.myNavigation.MyFragment"
    android:label="myNavigation"
    tools:layout="@layout/my_fragment"/>

At this time, you can see 4 navigations when running. If you want to modify the ui of the page, modify it under the corresponding fragment_layout file. The above file app:startDestination="@+id/navigation_home"is for setting the default startup page.
The function of adding examples
Our example mainly introduces this template instead of mvvm architecture, so the code is relatively simple.
HomeFragment code:

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of( this ).get( HomeViewModel.class );
        View root = inflater.inflate( R.layout.fragment_home, container, false );
        final TextView textView = root.findViewById( R.id.text_home );
        homeViewModel.getText().observe( this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText( s );
            }
        } );

        final Button button = root.findViewById( R.id.btn );
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText( homeViewModel.getDate() );
            }
        } );

        return root;
    }

}

HomeViewModel code:

public class HomeViewModel extends ViewModel {

    private MutableLiveData<String> mText;
    private Date now;
    public HomeViewModel() {
        String time = "现在是什么时间?";
        mText = new MutableLiveData<>();
        mText.setValue( time );
    }

    public LiveData<String> getText() {
        return mText;
    }

    public String getDate() {
        now = new Date();
        return now.toString();
    }

}

Well, that's it for the general content. If you have any questions, you are welcome to discuss it.

Guess you like

Origin blog.csdn.net/qq_42893430/article/details/92670784