[英]How can I change action bar title with different style in different fragments?
I am trying to change my 2 fragments action bar's with different titles. 我正在尝试用不同的标题更改我的2个片段操作栏。 However, I am getting variable fragment
might not have been initialized error in these lines: 但是,我在这些行中得到的可变fragment
可能未初始化错误:
ProfileFragment fragment = (ProfileFragment) fragment.get(0)
; ProfileFragment fragment = (ProfileFragment) fragment.get(0)
;
StartingTestFragment fragment2 = (StartingTestFragment) fragment2.get(0);
in CombineFragmentActivity
in onPageSelected
method.Thanks for helps. 在CombineFragmentActivity
在onPageSelected
method.Thanks的帮助。
CombineFragmentActivity.java CombineFragmentActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class CombineFragmentActivity extends AppCompatActivity {
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.combine_fragment_activity);
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new ArrayList<>();
fragments.add(new StartingTestFragment());
fragments.add(new ProfileFragment());
mPagerAdapter = new PagerAdapter1(this.getSupportFragmentManager(),fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(position == 0) {
ProfileFragment fragment = (ProfileFragment) fragment.get(0);
fragment.setActionBarTitle("Profil");
} else {
StartingTestFragment fragment2 = (StartingTestFragment) fragment2.get(0);
fragment2.setActionBarTitle("Anasayfa");
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
ProfileFragment.java ProfileFragment.java
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ProfileFragment extends Fragment implements AdapterView.OnItemSelectedListener {
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance() {
ProfileFragment fragment = new ProfileFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container, false);
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Typeface ubuntu_MI = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-MI.ttf");
Typeface ubuntu_L = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-L.ttf");
Typeface ubuntu_R = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-R.ttf");
/**
* Be carefull when trying to find a view element from a layout if the name is already defined in any layout
* AndroidStudio will not hint an error and you will end up with with ugly null pointer error
TextView question = (TextView) view.findViewById(R.id.textView7);
question.setTypeface(ubuntu_R);
TextView info = (TextView) view.findViewById(R.id.textView6);
info.setTypeface(ubuntu_R);
*/
}
public void setActionBarTitle(String title) {
Typeface ubuntu_MI = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-MI.ttf");
// Get the ActionBar
android.support.v7.app.ActionBar ab = ((AppCompatActivity)getActivity()).getSupportActionBar();
// Create a TextView programmatically.
TextView tv = new TextView(getActivity());
// Create a LayoutParams for TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
// Apply the layout parameters to TextView widget
tv.setLayoutParams(lp);
// Set text to display in TextView
// This will set the ActionBar title text
tv.setText(title);
// Set the text color of TextView
// This will change the ActionBar title text color
tv.setTextColor(Color.parseColor("#FFF5EE"));
// Center align the ActionBar title
tv.setGravity(Gravity.CENTER_HORIZONTAL);
// Set the serif font for TextView text
// This will change ActionBar title text font
tv.setTypeface(ubuntu_MI);
// Underline the ActionBar title text
// tv.setPaintFlags(tv.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);
// Set the ActionBar title font size
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,24);
// Display a shadow around ActionBar title text
//tv.setShadowLayer(
// 1.f, // radius
// 2.0f, // dx
// 2.0f, // dy
// Color.parseColor("#FF8C00") // shadow color
//);
// Set the ActionBar display option
ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// Finally, set the newly created TextView as ActionBar custom view
ab.setCustomView(tv);
}
public boolean onOptionsItemSelected(MenuItem item) {
//Action Bar' daki settings kısmına basıldığında ne yapacağını söylüyoruz.
if(item.getItemId() == R.id.settings){
Toast.makeText(getActivity(), "Ayarlara basıldı", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_profile_activity, menu);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
StartingTestFragment.java StartingTestFragment.java
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
public class StartingTestFragment extends Fragment implements AdapterView.OnItemSelectedListener {
private Spinner spinner;
ArrayAdapter<CharSequence> adapter;
public StartingTestFragment() {
// Required empty public constructor
}
public static StartingTestFragment newInstance() {
StartingTestFragment fragment = new StartingTestFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_startingtest, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
spinner = (Spinner)view.findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(getActivity(),R.array.simple_spinner_dropdown_item,R.layout.spinner_item);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Typeface ubuntu_L = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-L.ttf");
Typeface ubuntu_R = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-R.ttf");
TextView info = (TextView) view.findViewById(R.id.textView6);
TextView question = (TextView) view.findViewById(R.id.textView7);
info.setTypeface(ubuntu_R);
question.setTypeface(ubuntu_R);
}
public void setActionBarTitle(String title) {
Typeface ubuntu_MI = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-MI.ttf");
// Get the ActionBar
android.support.v7.app.ActionBar ab = ((AppCompatActivity)getActivity()).getSupportActionBar();
// Create a TextView programmatically.
TextView tv = new TextView(getActivity());
// Create a LayoutParams for TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView
// Apply the layout parameters to TextView widget
tv.setLayoutParams(lp);
// Set text to display in TextView
// This will set the ActionBar title text
tv.setText(title);
// Set the text color of TextView
// This will change the ActionBar title text color
tv.setTextColor(Color.parseColor("#FFF5EE"));
// Center align the ActionBar title
tv.setGravity(Gravity.CENTER_HORIZONTAL);
// Set the serif font for TextView text
// This will change ActionBar title text font
tv.setTypeface(ubuntu_MI);
// Underline the ActionBar title text
// tv.setPaintFlags(tv.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);
// Set the ActionBar title font size
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,24);
// Display a shadow around ActionBar title text
//tv.setShadowLayer(
// 1.f, // radius
// 2.0f, // dx
// 2.0f, // dy
// Color.parseColor("#FF8C00") // shadow color
//);
// Set the ActionBar display option
ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// Finally, set the newly created TextView as ActionBar custom view
ab.setCustomView(tv);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
// Whatever you want to happen when the first item gets selected
break;
case 1:
// Whatever you want to happen when the second item gets selected
break;
case 2:
// Whatever you want to happen when the thrid item gets selected
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
ERROR: FATAL EXCEPTION: main java.lang.ClassCastException: com.example.khas.memorizingwords.ProfileFragment cannot be cast to com.example.khas.memorizingwords.StartingTestFragment at com.example.khas.memorizingwords.CombineFragmentActivity$1.onPageSelected(CombineFragmentActivity.java:46) at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1862) at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:625) at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:609) at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2176) at android.view.View.dispatchTouchEvent(View.java:7127) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2170) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1905) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup. 错误:致命例外:main java.lang.ClassCastException:com.example.khas.memorizingwords.ProfileFragment无法转换为com.example.khas.memorizingwords.StartingTestFragment的com.example.khas.memorizingwords.CombineFragmentActivity $ 1.onPageSelected(CombineFragmentActivity。 java:46)位于android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1862)位于android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:625)位于android.support.v4.view .android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2176)的.ViewPager.setCurrentItemInternal(ViewPager.java:609)在android.view的android.view.View.dispatchTouchEvent(View.java:7127)。位于android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1905)的ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2170)位于android.view.ViewGroup.dispatchTouchEvent(ViewGroup)的android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176) .java:1919),位于android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup。 java:2176) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919) at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176) at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919) at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1925) at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1379) at android.app.Activity.dispatchTouchEvent(Activity.java:2396) at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrappe 的android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919)的java:2176)的android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)的android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919)的java。 android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)在android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919)在android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)在android.view.ViewGroup com.android.internal.policy.impl的android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)的android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1919)的.dispatchTouchEvent(ViewGroup.java:1919)。 android.app.Activity.dispatchTouchEvent(Activity.java:2396)上com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1379)上的com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1379)上的PhoneWindow $ DecorView.superDispatchTouchEvent(PhoneWindow.java:1925) .support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrappe r.java:60) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1873) at android.view.View.dispatchPointerEvent(View.java:7307) at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3172) at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3117) at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4153) at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4132) at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4224) at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:171) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:125) at android.os.Looper.loop(Looper.java:124) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$Method r.java:60)位于com.android.internal.policy.impl.PhoneWindow $ DecorView.dispatchTouchEvent(PhoneWindow.java:1873)位于android.view.View.dispatchPointerEvent(View.java:7307)位于android.view.ViewRootImpl android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3117)上的.deliverPointerEvent(ViewRootImpl.java:3172)android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4153)上的android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4153) android.view.ViewRootImpl $ WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4224)处的java:4132)android.os.MessageQueue.nativePollOnce(Native Method)处的android.os.MessageQueue.nativePollOnce(Native Method)处的android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:171) .os.MessageQueue.next(MessageQueue.java:125)在android.os.Looper.loop(Looper.java:124)在android.app.ActivityThread.main(ActivityThread.java:4745)在java.lang.reflect。 com.android.internal.os.ZygoteInit $ Method上的java.lang.reflect.Method.invoke(Method.java:511)上的Method.invokeNative(本机方法) AndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) AndArgsCaller.run(ZygoteInit.java:786)位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)位于dalvik.system.NativeStart.main(本机方法)
Your fragment variable is not initialized and you are caling get on it. 您的fragment变量尚未初始化,因此请继续进行下去。 Also this is not the correct way. 同样,这不是正确的方法。 Try below code 试试下面的代码
@Override
public void onPageSelected(int position) {
if(position == 0) {
ProfileFragment fragment = (ProfileFragment) getSupportFragmentManager().getFragments().get(1)
fragment.setActionBarTitle("Profil");
} else {
StartingTestFragment fragment2 = (StartingTestFragment) getSupportFragmentManager().getFragments().get(0);
fragment2.setActionBarTitle("Anasayfa");
}
}
This is a better version and more general 这是一个更好的版本,更通用
@Override
public void onPageSelected(int position) {
Fragment fragment1 = getActivity().getSupportFragmentManager().getFragments().get(position);
if(fragment1 instanceof ProfileFragment) {
ProfileFragment fragment = (ProfileFragment) fragment1;
fragment.setActionBarTitle("Profil" );
}
else{
StartingTestFragment fragment = (StartingTestFragment) fragment1;
fragment.setActionBarTitle("Anasayfa");
}
}
}
This is the way to change title 这是更改标题的方法
setActionBarTitle(YOUR_TITLE);
use this instead of fragment.setACtionBarTitle 用它代替fragment.setACtionBarTitle
I think it is not guaranteed what the order of fragments is when retreived from manager. 我认为不能保证从经理那里拿回碎片的顺序是什么。 So simply do this 所以只需这样做
@Override
public void onPageSelected(int position) {
Fragment fragment1 = fragments.get(position);
if(fragment1 instanceof ProfileFragment) {
ProfileFragment fragment = (ProfileFragment) fragment1;
fragment.setActionBarTitle("Profil" );
}
else{
StartingTestFragment fragment = (StartingTestFragment) fragment1;
fragment.setActionBarTitle("Anasayfa");
}
}
Note: Make your fragments list final by doing this 注意:通过执行此操作,使片段列表最终化
final List<Fragment> fragments = new ArrayList<>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.