Java android更改颜色选项卡选中选项卡

时间:2017-05-15 07:16:36

标签: java android tabs

我想更改所选的背景颜色标签。我想要选择颜色背景我的选项卡上的绿色选中并将颜色背景未选中的选项卡更改为#a8a8a8

但是当我在日志中滑动时,我看到了这一点:

 Process: pl.smok, PID: 28410


java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
                                                                            at pl..smok.ui.activity.MainActivity$2.onTabUnselected(MainActivity.java:163)
                                                                            at android.support.design.widget.TabLayout.dispatchTabUnselected(TabLayout.java:1163)
                                                                            at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1149)
                                                                            at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1124)
                                                                            at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1419)
                                                                            at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1524)
                                                                            at android.view.View$PerformClick.run(View.java:22526)
                                                                            at android.os.Handler.handleCallback(Handler.java:739)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:158)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:7224)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

这是完整的代码:

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.view_pager)
    ViewPager viewPager;

    @BindView(R.id.tab_layout)
    TabLayout tabLayout;

    ActionBar actionBar;
    SharedPreferences sp;
    SharedPreferences.Editor editor;
    int choose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
        editor = sp.edit();
        choose = sp.getInt("screen", 1);
//        String token = FirebaseInstanceId.getInstance().getToken();
//        Log.e( "Token: ", token);
        if(choose == 1 )
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        else
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        actionBar = getSupportActionBar();
        hideActionBar();

        String[] tabs = {"start", "status", "wiadomości", "nowa wiadomość"};
        viewPager.setOffscreenPageLimit(4);
        viewPager.setAdapter(new PageAdapter(getFragmentManager(), tabs));

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){

            @Override
         public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
             }

            @Override
         public void onPageSelected(int position) {
          CommonUtil.hideKeyboard(MainActivity.this);
                  }

         @Override
         public void onPageScrollStateChanged(int state) {
            }
           });
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setupWithViewPager(viewPager);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.colorBrown));
        }

        getFragmentManager()
                .beginTransaction()
                .add(R.id.top_bar_container, new TopBarFragment(), TopBarFragment.class.getName())
                .commit();

        processIntent(getIntent());
        createTabIcons();
        setupTabIcons();
    }

    @Override
    protected void onResume() {
        super.onResume();

        choose = sp.getInt("screen", 1);

        if(choose == 1 )
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        else
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    private void setupTabIcons() {


//        tabLayout.getTabAt(1).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                tab.getIcon().mutate().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
                Log.e("tab count " , tab.getPosition() + " " );
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        App.getBus().register(this);
        runServices();
    }

    @Override
    protected void onStop() {
        super.onStop();
        App.getBus().unregister(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        processIntent(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    protected void processIntent(Intent intent) {
        if (intent != null && intent.getIntExtra(Const.KEY_GOTO, 0) == 1 && viewPager != null) {
            viewPager.setCurrentItem(2);
        }
    }

    @Subscribe
    public void onPermissionRequestedEvent(PermissionRequestedEvent event) {
        PermissionUtil.getPermission(this, event.getPermission());
    }

    @Subscribe
    public void onPermissionGrantedEvent(PermissionGrantedEvent event) {
        if (event.getPermission().equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
            runLocationService();
        }
    }

    @Subscribe
    public void onPageNavigateEvent(PageNavigateEvent event) {
        Intent intent;
        switch (event.getPage()) {
            case Const.APP_SETTINGS_LOCATION:
                CommonUtil.hideKeyboard(this);
                intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
                break;
            case Const.PAGE_START:
                viewPager.setCurrentItem(0);
                break;
            case Const.PAGE_STATUSES:
                viewPager.setCurrentItem(1);
                break;
            case Const.PAGE_MESSAGES:
                viewPager.setCurrentItem(2);
                break;
            case Const.PAGE_SEND_MESSAGE:
                viewPager.setCurrentItem(3);
                break;
            default: break;
        }
    }

    @Subscribe(sticky = true)
    public void onLoggedOutEvent(LoggedOutEvent event) {
        String user = Hawk.get(HawkConst.LOGIN_USER);
        String company = Hawk.get(HawkConst.LOGIN_COMPANY);
        String password = Hawk.get(HawkConst.LOGIN_PASSWORD);
        Hawk.clear();
        Hawk.put(HawkConst.LOGIN_USER, user);
        Hawk.put(HawkConst.LOGIN_COMPANY, company);
        Hawk.put(HawkConst.LOGIN_PASSWORD, password);
        stopLocationService();
        stopTrackerService();
        stopConfigService();

        FileUtil.clearDirs();

        Intent intent = new Intent(MainActivity.this, StartActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        App.getBus().removeStickyEvent(LoggedOutEvent.class);
    }

    @Subscribe
    public void onPhotoRequestedEvent(PhotoRequestedEvent event) {
        Intent intent;
        switch (event.getRequestCode()) {
            case Const.PHOTO_GALLERY:
                intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.choose_image_title)), event.getRequestCode());
                break;
            case Const.PHOTO_CAMERA:
                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtil.getOutputTempUri("images"));
                startActivityForResult(intent, event.getRequestCode());
                break;
            default: break;
        }
    }

    @Subscribe
    public void onFileViewRequestEvent(FileViewRequestEvent event) {
        File file = FileUtil.getFile(event.getEvent().getId());
        if (file == null) {
            Toast.makeText(this, getResources().getString(R.string.file_not_exists), Toast.LENGTH_LONG).show();
        } else {
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            try {
                String type = FileUtil.getMimeType(file.getPath());
                intent.setDataAndType(uri, type);
                startActivity(intent);
                App.getBus().post(new FileViewedEvent(event.getEvent()));
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    intent.setDataAndType(uri, "*/*");
                    startActivity(intent);
                    App.getBus().post(new FileViewedEvent(event.getEvent()));
                } catch (Exception ee) {
                    ee.printStackTrace();
                    Toast.makeText(this, getResources().getString(R.string.no_file_app), Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    @Subscribe
    public void onHideKeyboardEvent() {
        CommonUtil.hideKeyboard(this);
           }

    @Subscribe
    public void onMoveAppBackgroundEvent(MoveAppBackgroundEvent event) {
        moveTaskToBack(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Const.PHOTO_GALLERY:
                    App.getBus().postSticky(new PhotoSelectedEvent(data.getData())); break;
                case Const.PHOTO_CAMERA:
                    Uri uri = FileUtil.renameFile(App.getConfigRepository().getPhotoMaxWidth());
                    App.getBus().postSticky(new PhotoSelectedEvent(uri)); break;
                default: break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Const.PERMISSIONS_REQUEST_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    App.getBus().post(new PermissionGrantedEvent(Manifest.permission.ACCESS_FINE_LOCATION));
                }
                break;
            default:
                break;
        }
    }

    protected void runServices() {
        if (LocationUtil.isLocationEnabled(getBaseContext())) {
            if (checkPermission()) {
                runLocationService();
            }
        } else {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage(getResources().getString(R.string.location_settings_disabled));
            dialog.setPositiveButton(getString(R.string.go_to_location_settings), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    App.getBus().post(new PageNavigateEvent(Const.APP_SETTINGS_LOCATION));
                }
            });
            dialog.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    finish();
                }
            });
            dialog.show();
        }
        runTrackerService();
        runConfigService();
    }

    protected void runLocationService() {
        startService(new Intent(this, LocationService.class));
    }

    protected void stopLocationService() {
        stopService(new Intent(this, LocationService.class));
    }

    protected void runTrackerService() {
        startService(new Intent(this, TrackerService.class));
    }

    protected void stopTrackerService() {
        stopService(new Intent(this, TrackerService.class));
    }

    protected void runConfigService() {
        startService(new Intent(this, ConfigService.class));
    }

    protected void stopConfigService() {
        stopService(new Intent(this, ConfigService.class));
    }

    protected boolean checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            App.getBus().post(new PermissionRequestedEvent(Manifest.permission.ACCESS_FINE_LOCATION));

            return false;
        }

        return true;
    }

    protected void hideActionBar() {
        if (actionBar != null) {
            actionBar.hide();
        }
    }

    private void createTabIcons(){
    }
}

这是此活动的xml代码。 activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="#fff"
    tools:context="pl.eltegps.smokkomunikator.ui.activity.MainActivity">

    <FrameLayout
        android:id="@+id/top_bar_container"
        android:layout_width="match_parent"
        android:layout_height="70dp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/top_bar_container">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="?attr/actionBarSize">

            <android.support.v4.view.ViewPager
                android:id="@+id/view_pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_vertical_margin"
                android:paddingRight="@dimen/activity_vertical_margin"
                android:paddingTop="@dimen/activity_vertical_margin" />
        </LinearLayout>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="center_horizontal"
            android:minHeight="?attr/actionBarSize"
            android:paddingTop="@dimen/activity_vertical_margin"
            app:tabGravity="center"
            app:tabIndicatorColor="#fff"
            app:tabMode="scrollable"
            app:tabTextAppearance="@style/MyCustomTextAppearance" />

    </RelativeLayout>

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

您好,您可以在xml中设置此颜色,无需编写代码

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="35dp"
    app:tabSelectedTextColor="@color/colorSplashBackground"
    app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
    app:tabTextColor="@color/colorBottomLine">

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

这将是标签布局的xml,你必须在行中传递颜色

 app:tabSelectedTextColor="@color/colorSplashBackground"