简体   繁体   English

工具栏不显示微调器

[英]Toolbar doesn't show Spinner

UPDATED更新
I try to add Spinner to Toolbar programmatically.我尝试以编程方式将Spinner添加到Toolbar So, I wrote the next code: ToolbarSpinnerAdapter :所以,我写了下一个代码: ToolbarSpinnerAdapter

public class ToolbarSpinnerAdapter extends BaseAdapter {

    public static final int NONE = -1;

    private final LayoutInflater mInflater;
    private List<String> mItems = new ArrayList<>();
    private int mSelectedPosition = NONE;
    private Drawable mSelector;

    public ToolbarSpinnerAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
        mSelector = VectorDrawable.getDrawable(context, R.drawable.ic_done_green_24dp);
        final int color = ContextCompat.getColor(context, R.color.primary);
        mSelector.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP));
    }

    public void setSelection(final int position) {
        mSelectedPosition = position;
    }

    public int getSelection() {
        return mSelectedPosition;
    }

    public void add(final String item) {
        mItems.add(item);
    }

    public void addAll(String[] items) {
        Collections.addAll(this.mItems, items);
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Object getItem(final int position) {
        return mItems.get(position);
    }

    @Override
    public long getItemId(final int position) {
        return position;
    }

    @Override
    public View getDropDownView(final int position, View view, ViewGroup parent) {

        if (view == null || !view.getTag().toString().equals("DROPDOWN")) {
            view = mInflater.inflate(R.layout.toolbar_spinner_dropdown_item, parent, false);
            view.setTag("DROPDOWN");
        }

        TextView textView = (TextView) view.findViewById(android.R.id.text1);
        textView.setText(getTitle(position));

        if(position == mSelectedPosition) {
            textView.setCompoundDrawablesWithIntrinsicBounds(null, null, mSelector, null);
        } else {
            textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }

        return view;
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {

        if (view == null || !view.getTag().toString().equals("NON_DROPDOWN")) {
            view = mInflater.inflate(R.layout.toolbar_spinner_item, parent, false);
            view.setTag("NON_DROPDOWN");
        }

        TextView textView = (TextView)view.findViewById(android.R.id.text1);
        textView.setText(getTitle(position));

        return view;
    }

    private String getTitle(final int position) {
        return mItems.get(position);
    }
}

Code of using:使用代码:

protected void initToolbar(Toolbar toolbar) {
    final MainActivity activity = (MainActivity) getActivity();
    activity.setSupportActionBar(toolbar);
    mDrawerToggle = new ActionBarDrawerToggle(activity, activity.getDrawerLayout(), toolbar, R.string.app_name, R.string.app_name);
    activity.getDrawerLayout().addDrawerListener(mDrawerToggle);
    ActionBar actionBar = activity.getSupportActionBar();
    Context toolbarContext;

    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        mDrawerToggle.syncState();
        toolbarContext = activity.getSupportActionBar().getThemedContext();
    } else {
        toolbarContext = getContext();
    }

    mWeekSpinner = new Spinner(toolbarContext);
    ToolbarSpinnerAdapter adapter = new ToolbarSpinnerAdapter(toolbarContext);
    mWeekSpinner.setAdapter(adapter);
    toolbar.addView(mWeekSpinner);
    final String[] weekNames = WeekUtils.getWeekNames(getContext(), mTimetable.getWeekCount());
    adapter.addAll(weekNames);
    final int currentWeek = WeekUtils.getCurrentWeek(mTimetable);
    adapter.setSelection(currentWeek - 1);
    mWeekSpinner.setSelection(currentWeek - 1);
}

Fragment layout xml:片段布局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:context=".activity.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"
            android:background="@drawable/bg_tabs"
            app:tabGravity="fill"
            app:tabIndicatorColor="@color/primary"
            app:tabIndicatorHeight="6dp"
            app:tabMode="scrollable"
            app:tabSelectedTextColor="@color/primary"
            app:tabTextColor="@color/black_54"/>

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

    <!-- Body views -->

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

Spinner item view xml: Spinner 项目视图 xml:

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primary"
    android:gravity="center_vertical"
    android:minHeight="?attr/listPreferredItemHeightSmall"
    android:paddingLeft="12dp"
    android:paddingRight="12dp"
    android:textAppearance="?attr/textAppearanceListItemSmall"/>

Activity theme:活动主题:

<style name="Theme.Paper" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="windowActionModeOverlay">true</item>
</style>

Result:结果:
截屏 截图 2 How?如何? I understand nothing already... How to fix it?我什么都不懂...如何解决?

Let us fix this once and for all now:现在让我们一劳永逸地解决这个问题:

Try this:尝试这个:

First - inside strings.xml首先 - 在 strings.xml 中

<string-array name="months">
    <item>January</item>
    <item>February</item>
    <item>March</item>
    <item>April</item>
    <item>May</item>
    <item>June</item>
    <item>July</item>
    <item>August</item>
</string-array>

You can simply replace with your real values;您可以简单地替换为您的真实值;

Second - in your main layout第二 - 在您的主要布局中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  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=".MainActivity">

  <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize" />

The point is to have your Toolbar inside the layout like you probably have done above.关键是将您的工具栏放在布局中,就像您在上面所做的那样。

Three - custom spinner layout三自定义微调器布局

Create a custom view for your spinner!为您的微调器创建自定义视图!

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/text1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:background="@color/colorPrimary"
  android:gravity="center_vertical"
  android:minHeight="?android:attr/listPreferredItemHeightSmall"
  android:paddingLeft="12dp"
  android:paddingRight="12dp"
  android:textAppearance="?android:attr/textAppearanceListItemSmall"  />

Four - MainActivity.java Here, we are going to complete the code.四——MainActivity.java这里,我们来完成代码。

public class MainActivity extends AppCompatActivity {

   private Toolbar toolbar = null;
   private String[] month = null;

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

     month = getResources().getStringArray(R.array.months);

     toolbar = (Toolbar) findViewById(R.id.toolbar);
     setSupportActionBar(toolbar);

     SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.months, R.layout
            .spinner_drop_down_item);
     Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext());
     navigationSpinner.setAdapter(spinnerAdapter);
     toolbar.addView(navigationSpinner, 0);

      navigationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(MainActivity.this,
                    "you selected: " + month[position],
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
     });

   }
}

Lastly, for theming, you should have the following in your styles.xml最后,对于主题,您的styles.xml 中应该包含以下内容

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionModeOverlay">true</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

Here is a repository I have created for the code above.这是我为上面的代码创建的存储库

I hope this helps you;我希望这可以帮助你; I have tried it and it worked just fine;我试过了,效果很好;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM