简体   繁体   English

Android - 何时从Fragment调用Activity的方法

[英]Android - When to call method of Activity from Fragment

I have an Activity which has Toolbars . 我有一个包含ToolbarsActivity When I move to Fragment A, the Toolbar needs to be changed specifically for Fragment A. 当我移动到Fragment A时,需要专门为Fragment A更改Toolbar

Fragment A contains 4 other Fragments as A is a FragmentPager . Fragment A包含4个其他Fragments因为A是FragmentPager

I called the method of the Activity like : 我调用了Activity的方法,如:

((NewsfeedActivity)getActivity()).changeTitleBesideIcon("Purchases");
        ((NewsfeedActivity)getActivity()).changeIcon(getResources().getDrawable(R.drawable.purchase));
        ((NewsfeedActivity)getActivity()).changeBackground(getResources().getColor(R.color.purpleC));
        ((NewsfeedActivity)getActivity()).hideToolbarBottomMarketplace();

Somehow, the icon doesn't get changed, BUT the title does, along with the color.. I even set the method to setVisibility(View.VISIBLE); 不知何故,图标不会改变,但标题不会改变颜色..我甚至将方法设置为setVisibility(View.VISIBLE); on the icon.. 在图标上..

Is there a specific state where that kind of method needs to be called? 是否存在需要调用这种方法的特定状态? Or am I just doing it wrong? 或者我只是做错了?

Update 更新

This is my changeIcon method 这是我的changeIcon方法

public void changeIcon(Drawable imageDrawable){
    toolbarImage.setVisibility(View.GONE);
    toolbarIcon.setVisibility(View.VISIBLE);
    toolbarIcon.setImageDrawable(imageDrawable);
}

toolbarImage is an ImageView located in the Toolbar toolbarImage是位于ToolbarImageView

This is how it is : 这是这样的:

<Toolbar>
    <RelativeLayout>
        <ImageView> //Toolbar Image
        <ImageView>// Toolbar Icon
    </RelativeLayout>
</Toolbar>

And I'm calling the methods in the onCreateView() .. 我正在调用onCreateView()的方法..

try it. 试试吧。

public void changeIconToolbar(int resId){
    getSupportActionBar().setHomeAsUpIndicator(resId);
}

it work for me 它对我有用

Well, now I can see that you possibly use Toolbar (rather than ActionBar ) and once again I assume that the Toolbar is the toolbar added in API level 21 rather than AppCompat Toolbar . 好吧,现在我可以看到你可能使用Toolbar (而不是ActionBar ),我再次假设Toolbar是在API级别21而不是AppCompat工具 栏中添加的工具栏

In order to use this toolbar , I assume that you have called setActionBar (toolbar) to replace the ActionBar with the toolbar from your layout. 为了使用这个toolbar ,我假设您已调用setActionBar (toolbar)ActionBar替换为布局中的工具栏。

NOTE: Without calling this setActionBar (toolbar) , your activity will continue using the default ActionBar (in onCreate() ) and nothing will be shown. 注意:如果不调用此setActionBar (toolbar) ,您的活动将继续使用默认的ActionBar (在onCreate() ),并且不会显示任何内容。

Now, when the toolbar is in its place. 现在,当工具栏在它的位置。 I think your code will work. 我认为你的代码会起作用。

PS: I recommend to use AppCompat Toolbar PS:我建议使用AppCompat工具栏

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

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