我有一个MainActivity类,是否可以使用Button onclicklistner启动片段类
主要活动类:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button r_btn=(Button) findViewById(R.id.btn_register);
r_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, test.class);
startActivity(i);
}
});
片段类
public class test extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_test, container, false);
rootView.findViewById(R.id.label1);
// Inflate the layout for this fragment
return rootView;
}
}
任何提示都会有所帮助..
答案 0 :(得分:2)
是的,你可以,但你不能处理像活动这样的片段,所以你不能使用startActivity
方法。使用片段管理器调用片段
fragmentContainer = (RelativeLayout) findViewById(R.id.fragmentContainer);
r_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
replaceFragmentInContainer(new test(), fragmentContainer.getId(), getSupportFragmentManager());
}
});
public void replaceFragmentInContainer(Fragment DestinationFragment,int containerResourceID,FragmentManager fragmentManager )
{
FragmentTransaction ft=fragmentManager.beginTransaction();
int viewResourceID = containerResourceID;
ft.replace(viewResourceID, DestinationFragment);
ft.commit();
}
您的容器在活动xml中将处理您的片段
<RelativeLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_below="@+id/toolbar"
android:layout_height="match_parent"
>
</RelativeLayout>
或者您可以查看this