简体   繁体   中英

Android ActionBar and Toolbar are not seen even when defined in xml

I have this layout and Fragment class:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/non_clickable_account_snackbar_constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <android.support.v7.widget.Toolbar
      android:id="@+id/my_toolbar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="@string/my_title"
      android:layout_gravity="center"
      />
  <mylButton
      android:id="@+id/show_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:text="@string/show"/>
</FrameLayout>

and

public class myFragment extends Fragment {

  @Inject
  public myFragment() {}

  @Override
  public View onCreateView(
      LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) {
    View view =
        layoutInflater.inflate(
            R.layout.my_fragment, viewGroup, false /* attachToRoot */);

    AppCompatActivity activity = (AppCompatActivity) getActivity();
    activity.getSupportActionBar().setTitle(R.string.account_snackbar_title);
    activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    return view;
  }

}

I see this thread about the visual difference between ActionBar and a Toolbar.

However I don't seem to see any of them, just a blank page with a button.

在此处输入图片说明

Thanks to @Mike M. comment I have noticed my toolbar wasn't getting the content I wanted it to get.

For setting title from xml:

I should have replaced "android:setText" with android:setTitle

For setting title from code:

I was missing getting the toolbar view:

AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(view.findViewById(R.id.my_toolbar));
activity.getSupportActionBar().setTitle(R.string.show);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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