[英]In Android, override a method using Button onClick
I've got a Main Activity which is a search interface, when the user clicks a result in the list, the result details are displayed in a Fragment
. 我有一个Main Activity,它是一个搜索界面,当用户单击列表中的结果时,结果详细信息将显示在
Fragment
。 The Main Activity has an Action Bar, but in the details Fragment, the Action Bar is hidden. Main Activity有一个动作栏,但是在片段详细信息中,该动作栏是隐藏的。 To hide the Action Bar in the Fragment, I'm calling a method in the Main Activity from the Fragment Activity like this:
((SearchInterface)getActivity()).hideABar();
为了在片段中隐藏操作栏,我从片段活动中调用Main活动中的方法,如下所示:
((SearchInterface)getActivity()).hideABar();
. 。 Then when the user clicks the back button, they go back to the search interface and the Action Bar reappears.
然后,当用户单击“后退”按钮时,他们将返回搜索界面,并重新出现操作栏。 Doing that is a bit more complex than simply calling a method.
这样做比简单地调用方法要复杂一些。 I set up an
Interface
in the Main Activity and override the method in the Fragment like this: Main Activity: 我在Main Activity中设置了一个
Interface
并覆盖了Fragment中的方法,如下所示: Main Activity:
public interface Callback {
public void onBackPressedCallback();
}
@Override
public void onBackPressed() {
super.onBackPressed();
if(fragBackPressed != null)
fragBackPressed.onBackPressedCallback();
checkActionBarState();
}
...
public void checkActionBarState(){
bar_AB = getSupportActionBar();
boolean barVisible = bar_AB.isShowing();
if(barVisible){
Toast.makeText(getApplicationContext(),"ActionBar WAS Visible",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"ActionBar WAS NOT Visible",Toast.LENGTH_LONG).show();
bar_AB.show();
}
}
Fragment: 分段:
@Override
public void onBackPressedCallback() {
Log.d("SSIVideoFrag", "checking action bar state");
}
So now, when the user presses the Back button while in the Details Fragment, they go back to Main Activity and the Action Bar reappears. 因此,现在,当用户在“详细信息片段”中按下“返回”按钮时,他们将返回到“主活动”,并且将重新显示操作栏。 Now I'd like to add a button in the Details Fragment that does what clicking the Back button does, but I can't figure out how to do it.
现在,我想在“详细信息片段”中添加一个按钮,该按钮的功能与单击“后退”按钮的功能相同,但是我不知道该怎么做。 I don't know how to override the
onBackPressedCallback()
method from within the onClick of a Button: 我不知道如何从按钮的onClick内重写
onBackPressedCallback()
方法:
back_BTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//--- what to do here?
}
});
simple: 简单:
getFragmentManager().popBackStack();
https://developer.android.com/reference/android/app/FragmentManager.html#popBackStack() https://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
ps.: that's not an actual back press, your onBackPressed
will not be called. ps .:这不是实际的后按,因此不会调用您的
onBackPressed
。 But the fragment will be removed, just like in a back press. 但是片段将被删除,就像在反向压片中一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.