我有一個簡單的佈局,其中包含回收站視圖和框架佈局,我希望顯示一個片段。我的想法是,我有一個數據列表顯示在回收視圖 - (我注入cardview與imageView和textView)和frameLayout這是我的片段的容器。一旦一個項目被點擊,它應該顯示一個包含細節的片段。我知道這是一個更好的方法是有兩個片段並進行更改,但由於我只有一個活動和兩個屏幕,我只想要一個片段。在活動中點擊按鈕時在回收站視圖和片段之間切換
這裏的佈局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="michael.com.ui.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#00000000"/>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/donut_progress"
android:layout_alignParentStart="true"/>
</RelativeLayout>
==
public class MainActivity extends AppCompatActivity {
@BindView(R.id.list) RecyclerView mRecyclerView;
@BindView(R.id.container) FrameLayout container;
@Inject Service service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setRecyclerView();
TeamPresenter mPresenter = new TeamPresenter(service, this);
mPresenter.getContacts();
}
private void setRecyclerView() {
mRecyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));
}
@Override
public void onLoadingFailed(String error) {
Toast.makeText(getApplicationContext(),error,Toast.LENGTH_LONG).show();
}
@Override
public void showContacts(Response response) {
ContactsAdapter mAdapter = new ContactsAdapter(response.getContacts(),
new ContactsAdapter.OnItemClickListener() {
@Override
public void onClick(Contacts item) {
initFragment(DetailsFragment.newInstance());
}
});
mRecyclerView.setAdapter(mAdapter);
}
private void initFragment(Fragment detailFragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.container, detailFragment, "TAG");
transaction.addToBackStack("TAG");
transaction.commit();
}
}
我知道,我也許可以setVisibility於無形RecyclerView當我初始化片段。但是,我如何處理片段中的pressBack按鈕以返回主屏幕?