我想根据点击的toolbar
更改热门fragment
,但似乎对我不起作用。
我想要的是当我点击fragment
时,顶部工具栏应该更改。例如,添加Add
按钮并更改Create Fragment
的工具栏标题。
Fragment.java
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
Toolbar toolbar123 = (Toolbar) v.findViewById(R.id.toolbar123);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar123);
//((MainActivity) getActivity()).getSupportActionBar().hide();
return v;
}
片段XML
<FrameLayout 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="com.example.rick.check_in.ui.EventCreatedFragment">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar123"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#131313"
android:minHeight="?attr/actionBarSize">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#00aaaaaa">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:text="Delete"
android:textColor="#fff"
android:textSize="16dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
答案 0 :(得分:3)
你可以这样做。一旦片段与其活动相关联,就会调用onAttach(Activity)
。
public class YourFragment extends Fragment {
private MainActivity mainActivity;
private Toolbar toolbar123;
public YourFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mainActivity = (MainActivity)activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
toolbar123 = (Toolbar)v.findViewById(R.id.toolbar123);
setupToolbar();
return v;
}
private void setupToolbar(){
toolbar123.setTitle(getString("Your Fragment Title"));
mainActivity.setSupportActionBar(toolbar123);
}
}