Java 如何显示Android自定义组件的片段?
我已经使用合并标记声明了一个自定义组件,该标记在我的应用程序中的多个位置使用。是否可以从此类调用Java 如何显示Android自定义组件的片段?,java,android,android-fragments,Java,Android,Android Fragments,我已经使用合并标记声明了一个自定义组件,该标记在我的应用程序中的多个位置使用。是否可以从此类调用getFragmentManager()或getSupportFragmentManager()?此类扩展了LinearLayout而不是活动。我要做的是显示这个自定义组件的一个新片段,但是这两个函数都不能访问。如何显示来自此自定义组件的新片段 以下是我的基本代码: public class SpecialTextBox extends LinearLayout implements View.OnC
getFragmentManager()
或getSupportFragmentManager()
?此类扩展了LinearLayout而不是活动。我要做的是显示这个自定义组件的一个新片段,但是这两个函数都不能访问。如何显示来自此自定义组件的新片段
以下是我的基本代码:
public class SpecialTextBox extends LinearLayout implements View.OnClickListener {
//......constructors
public void initialize(final Context context, AttributeSet attrs) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.special_box, this);
}
@Override
public void onClick(View view) {
super.callOnClick();
switch (view.getId()) {
case R.id.searchButton:
SearchFragment searchFragment = new SearchFragment(new DialogFragmentDismissHandler(), specialBox.getEditText().getText().toString());
searchFragment.show(dashboardActivity.getFragmentManager(), SearchFragment.class.toString());
}
}
}
XML:
您只能从FragmentActivity调用
getFragmentManager()
或getSupportFragmentManager()
。如果自定义视图位于片段活动
中,则可以执行此操作
FragmentActivity a = (FragmentActivity) getContext();
a.getFragmentManager()
我可以通过以下方式访问getFragmentManager():
Activity a = (Activity)(((ContextWrapper) getContext()).getBaseContext());
a.getFragmentManager();
传入对活动的引用?如何显示来自此自定义组件的新片段?-
视图
在其构造函数中接收一个上下文
引用(也可通过getContext()
获得)。如果您计划使用支持片段,请将该引用转换为某个活动或ActionBarActivity。当我尝试将getContext()转换为某个活动时,它会说无法将“android.view.ContextThemeWrapper”转换为“android.app.Activity”。这会导致错误“无法将“android.view.ContextThemeWrapper”转换为“android.app.Activity”。但这让我开始了正确的想法…谢谢你的帮助!不适用于我:java.lang.ClassCastException:android.app.ContextImpl不能强制转换为android.app.Activity
Activity a = (Activity)(((ContextWrapper) getContext()).getBaseContext());
a.getFragmentManager();