Как изменить активность при нажатии нижней кнопки навигации?

Я хочу использовать нижнюю панель навигации в своем существующем приложении для Android, но проблема в том, что весь экран является активностью, можно ли загружать активность, не скрывая нижнюю панель навигации.

пример: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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.support.v4.widget.NestedScrollView
        android:id="@+id/myScrollingContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Your loooooong scrolling content here. -->

    </android.support.v4.widget.NestedScrollView>
    <com.roughike.bottombar.BottomBar
        android:id="@+id/bottomBar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_gravity="bottom"
        app:bb_tabXmlResource="@xml/bottom_bar"
        app:bb_behavior="shy"/>

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

это моя базовая деятельность,

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        BottomBar bottomBar;
        bottomBar = (BottomBar) findViewById(R.id.bottomBar);
        bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(@IdRes int tabId) {
                if (tabId == R.id.matching) {
                    Log.i("matching","matching inside "+tabId);
                    Intent in=new Intent(getBaseContext(),Main2Activity.class);
                    startActivity(in);
                }else if (tabId == R.id.watchlist) {
                    Log.i("matching","watchlist inside "+tabId);
                    Intent in=new Intent(getBaseContext(),Main3Activity.class);
                    startActivity(in);
                }
            }
        });
    }
}

Main2Activity

public class Main2Activity extends MainActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main2);
        NestedScrollView dynamicContent = (NestedScrollView) findViewById(R.id.myScrollingContent);
        View wizard = getLayoutInflater().inflate(R.layout.activity_main2, null);
        dynamicContent.addView(wizard);

Main3Activity

public class Main3Activity extends MainActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main3);
        NestedScrollView dynamicContent = (NestedScrollView) findViewById(R.id.myScrollingContent);
        View wizard = getLayoutInflater().inflate(R.layout.activity_main3, null);
        dynamicContent.addView(wizard);


    }
}

манифест

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

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

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

</manifest>

person Sushil Dubey    schedule 19.01.2017    source источник
comment
можете предоставить скриншоты?   -  person Truong Hieu    schedule 19.01.2017
comment
Помимо вашего вопроса, Main3Activity даже не должна работать, потому что findViewById не может найти представления, если у вас нет представления контента.   -  person OneCricketeer    schedule 19.01.2017


Ответы (2)


Я решил эту проблему следующим образом:

1. Создайте одну BaseActivity с нижней панелью навигации.

 package com.example.apple.bottomnavbarwithactivity;

 import android.content.Intent;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.RadioButton;
 import android.widget.RadioGroup;

public class BaseActivity extends AppCompatActivity {


RadioGroup radioGroup1;
RadioButton deals;

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


    radioGroup1=(RadioGroup)findViewById(R.id.radioGroup1);
    deals = (RadioButton)findViewById(R.id.deals);
    radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId)
        {
            Intent in;
            Log.i("matching", "matching inside1 bro" + checkedId);
            switch (checkedId)
            {
                case R.id.matching:
                    Log.i("matching", "matching inside1 matching" +  checkedId);
                    in=new Intent(getBaseContext(),MatchingActivity.class);
                    startActivity(in);
                    overridePendingTransition(0, 0);
                    break;
                case R.id.watchList:
                    Log.i("matching", "matching inside1 watchlistAdapter" + checkedId);

                    in = new Intent(getBaseContext(), WatchlistActivity.class);
                    startActivity(in);
                    overridePendingTransition(0, 0);

                    break;
                case R.id.rates:
                    Log.i("matching", "matching inside1 rate" + checkedId);

                    in = new Intent(getBaseContext(),RatesActivity.class);
                    startActivity(in);
                    overridePendingTransition(0, 0);
                    break;
                case R.id.listing:
                    Log.i("matching", "matching inside1 listing" + checkedId);
                    in = new Intent(getBaseContext(), ListingActivity.class);
                    startActivity(in);
                    overridePendingTransition(0, 0);
                    break;
                case R.id.deals:
                    Log.i("matching", "matching inside1 deals" + checkedId);
                    in = new Intent(getBaseContext(), DealsActivity.class);
                    startActivity(in);
                    overridePendingTransition(0, 0);
                    break;
                default:
                    break;
            }
        }
    });
   }
 }

Макет BaseActivity с именем base_activity.xml

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:elevation="10dp"
        android:background="@color/white"
        android:id="@+id/bottonNavBar"
        android:paddingTop="5dp"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:foregroundGravity="bottom">


        <RadioGroup
            android:id="@+id/radioGroup1"
            android:gravity="center"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:baselineAligned="false">

            <RadioButton
                android:layout_width="match_parent"
                android:gravity="center"
                android:layout_height="match_parent"
                android:text="Matching"
                android:layout_weight="1"
                android:button="@null"
                android:padding="2dp"
                android:checked="false"
                android:textSize="12sp"
                android:drawableTop="@drawable/selector_matching"
                android:textColor="@drawable/selector_nav_text"
                android:id="@+id/matching"/>

            <RadioButton
                android:layout_width="match_parent"
                android:gravity="center"
                android:layout_height="match_parent"
                android:button="@null"
                android:layout_weight="1"
                android:padding="2dp"
                android:checked="false"
                android:textSize="12sp"
                android:drawableTop="@drawable/selector_watchlist"
                android:textColor="@drawable/selector_nav_text"
                android:id="@+id/watchList"
                android:text="Watchlist"/>

            <RadioButton
                android:layout_width="match_parent"
                android:gravity="center"
                android:layout_height="match_parent"
                android:id="@+id/rates"
                android:button="@null"
                android:paddingTop="5dp"
                android:paddingBottom="2dp"
                android:paddingLeft="2dp"
                android:paddingRight="2dp"
                android:layout_weight="1"
                android:checked="false"
                android:textSize="12sp"
                android:drawableTop="@drawable/selector_rates"
                android:textColor="@drawable/selector_nav_text"
                android:text="Rates"/>
            <RadioButton
                android:layout_width="match_parent"
                android:gravity="center"
                android:layout_height="match_parent"
                android:button="@null"
                android:padding="2dp"
                android:checked="false"
                android:layout_weight="1"
                android:textSize="12sp"
                android:drawableTop="@drawable/selector_deals"
                android:textColor="@drawable/selector_nav_text"
                android:id="@+id/deals"
                android:text="Deals"/>
            <RadioButton
                android:layout_width="match_parent"
                android:gravity="center"
                android:layout_height="match_parent"
                android:button="@null"
                android:padding="2dp"
                android:checked="false"
                android:layout_weight="1"
                android:textSize="12sp"
                android:drawableTop="@drawable/selector_listing"
                android:textColor="@drawable/selector_nav_text"
                android:id="@+id/listing"
                android:text="Listing"/>


        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/dynamicContent"
        android:orientation="vertical"
        android:layout_marginBottom="56dp"
        android:background="@color/white"
        android:layout_gravity="bottom">
    </LinearLayout>

2.extend BaseActivity in all the activity that you want to open on bottom nav click and also need to inflate the activity layouts For example, I have created five sample activity.

i] MatchingActivity.

  package com.example.apple.bottomnavbarwithactivity;

    import android.graphics.Color;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
              //extends our custom BaseActivity
    public class MatchingActivity extends BaseActivity {
        LinearLayout dynamicContent,bottonNavBar;

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


                       //dynamically include the  current activity      layout into  baseActivity layout.now all the view of baseactivity is   accessible in current activity.
            dynamicContent = (LinearLayout)  findViewById(R.id.dynamicContent);
            bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar);
            View wizard = getLayoutInflater().inflate(R.layout.activity_matching, null);
            dynamicContent.addView(wizard);


              //get the reference of RadioGroup.

            RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton rb=(RadioButton)findViewById(R.id.matching);

                 // Change the corresponding icon and text color on nav button click.

            rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_matching_clicked, 0,0);
            rb.setTextColor(Color.parseColor("#3F51B5"));
        }

    }

ii]Активность списка наблюдения

 package com.example.apple.bottomnavbarwithactivity;

    import android.graphics.Color;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;

    public class WatchlistActivity extends AppCompatActivity {
        LinearLayout dynamicContent,bottonNavBar;

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

            dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent);
            bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar);
            View wizard = getLayoutInflater().inflate(R.layout.activity_watchlist1, null);
            dynamicContent.addView(wizard);

            RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton rb=(RadioButton)findViewById(R.id.watchList);
            rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.favourite_heart_selected, 0,0);
            rb.setTextColor(Color.parseColor("#3F51B5"));
        }
    }

iii]Рейтинг активности

  package com.example.apple.bottomnavbarwithactivity;

    import android.graphics.Color;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;

    public class RatesActivity extends BaseActivity {
        LinearLayout dynamicContent,bottonNavBar;

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

            dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent);
            bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar);
            View wizard = getLayoutInflater().inflate(R.layout.activity_rates, null);
            dynamicContent.addView(wizard);

            RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton rb=(RadioButton)findViewById(R.id.rates);
            rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_rate_clicked, 0,0);
            rb.setTextColor(Color.parseColor("#3F51B5"));
        }
    }

iv] ListingActivity

 package com.example.apple.bottomnavbarwithactivity;

    import android.graphics.Color;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;

    public class ListingActivity extends BaseActivity {
        LinearLayout dynamicContent,bottonNavBar;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
             //setContentView(R.layout.activity_listing);



            dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent);
            bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar);
            View wizard = getLayoutInflater().inflate(R.layout.activity_listing, null);
            dynamicContent.addView(wizard);

            RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton rb=(RadioButton)findViewById(R.id.listing);
            rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_listing_clicked, 0,0);
            rb.setTextColor(Color.parseColor("#3F51B5"));
        }
    }

v] Активность по сделкам

 package com.example.apple.bottomnavbarwithactivity;

    import android.graphics.Color;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;

    public class DealsActivity extends BaseActivity {

        LinearLayout dynamicContent,bottonNavBar;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.activity_deals);
            dynamicContent = (LinearLayout) findViewById(R.id.dynamicContent);
            bottonNavBar= (LinearLayout) findViewById(R.id.bottonNavBar);
            View wizard = getLayoutInflater().inflate(R.layout.activity_deals, null);
            dynamicContent.addView(wizard);

            RadioGroup rg=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton rb=(RadioButton)findViewById(R.id.deals);
            rb.setCompoundDrawablesWithIntrinsicBounds( 0,R.drawable.ic_deals_clicked, 0,0);
            rb.setTextColor(Color.parseColor("#3F51B5"));



        }
    }

Примечание. убедитесь, что вы правильно обрабатываете обратное нажатие. Я не писал никакого кода для обратного нажатия.

введите описание изображения здесь

введите описание изображения здесь

введите описание изображения здесь

введите описание изображения здесь

введите описание изображения здесь

person Sushil Dubey    schedule 06.04.2017
comment
Я реализую этот код, чего я не могу понять, так это того, как избежать повторного создания действий? Я имею в виду, что я теряю состояние активности, и оно снова создается с нуля. - person Giuseppe Capoluongo; 17.10.2017
comment
вы можете сохранить состояние активности, проверив это сообщение - stackoverflow.com/questions/151777/ - person Sushil Dubey; 24.10.2017

С Activity вы должны объявить и инициализировать этот BottomBar каждый раз, когда вы загружаете этот activity.

Что касается вашей проблемы, мой ответ НЕТ.

Кстати, вы можете использовать Fragment, который поможет вам решить эту проблему довольно хорошо.

Пора узнать что-то новое, бро.

ИЗМЕНИТЬ

Вы привносите Fragment только в 1 действие. И пусть BottomBar внутри Activity, пока все остальные просматривают и устанавливают данные внутри Fragment.

Просто попробуйте!

person Truong Hieu    schedule 19.01.2017
comment
мое приложение имеет пять основных экранов, и все они являются активными, теперь очень сложно и много времени преобразовать эти действия в фрагмент, есть ли какой-либо способ, чтобы я мог получить нижний навигационный вид с моими существующими действиями. - person Sushil Dubey; 19.01.2017
comment
Вы исследовали Fragment? Я думаю, что это будет не слишком сложно и не так уж много работы, всего 5 экранов :D. И Activity, и Fragment мало чем отличаются. Вы должны изменить для последующего обслуживания. - person Truong Hieu; 20.01.2017
comment
Как насчет настроек активности? Могу ли я разместить его в нижней панели навигации? - person Anton Makov; 01.10.2019