gpt4 book ai didi

java - 如何横向并排显示 2 个 fragment

转载 作者:行者123 更新时间:2023-11-30 11:04:56 46 4
gpt4 key购买 nike

我有一个托管 ListFragmentA 的 Activity1。
单击列表中的一个项目时,我启动 Activity2 托管 ListFragmentB
无论是纵向还是横向,我一次都看到 1 个列表。
当我处于横向模式(或者我猜是在平板电脑中)时,我很感兴趣看到这两个 fragment 。
IE。显示左侧的 ListFragmentA 和右侧的 ListFragmentB。这样,当用户按下 ListFragmentA 中的某个项目时,就会显示 ListFragmentB 中的正确数据。
这是怎么做到的?在横向模式下通过布局在我看来很乏味/错误,并且不确定它是如何完成的。
有没有我可以研究的好例子?

最佳答案

纵向模式的 fragment_layout.xml 是:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<fragment
android:id="@+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="edu.dartmouth.cs.FragmentLayout$TitlesFragment" />

</FrameLayout>

在横向模式下,单个 Activity (FragmentLayout) 处理这两个 fragment 。我们还将考虑以编程方式插入 fragment 。考虑景观 res/layout-land/fragment_layout。

横向模式的 fragment_layout.xml 是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >

<fragment
android:id="@+id/titles"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
class="edu.dartmouth.cs.FragmentLayout$TitlesFragment" />

<FrameLayout
android:id="@+id/details"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="?android:attr/detailsElementBackground" />

</LinearLayout>

如果您在 TitlesFragment: onActivityCreated()(在 FragmentLayout onCreate() 返回时调用)中注释掉下面显示的代码行,那么您将在上面的 frame_layout 加载时看到空白。如果该行未添加回去,则 DetailsFragment 不会加载到用户从列表中选择一个项目之前 - 此时会创建 DetailsFragment 并将其放入 FrameLayout。

 public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

**snippet**

if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
} else {

FragmentLayout(主要 Activity )在 onCreate() 期间以通常的方式应用布局:

public class FragmentLayout extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// root view inflated
setContentView(R.layout.fragment_layout);
}

当用户单击 ListFragment 中的一个项目时,将调用 onListItemClick() 回调,进而调用 showDetails(position) 以开始

 @Override
public void onListItemClick(ListView l, View v, int position, long id) {

Toast.makeText(getActivity(),
"onListItemClick position is" + position, Toast.LENGTH_LONG)
.show();

showDetails(position);
}

标题 fragment

该 fragment 使用辅助函数来显示所选项目的详细信息。

 public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;

// onActivityCreated() is called when the activity's onCreate() method
// has returned.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

// You can use getActivity(), which returns the activity associated
// with a fragment.
// The activity is a context (since Activity extends Context) .

Toast.makeText(getActivity(), "TitlesFragment:onActivityCreated",
Toast.LENGTH_LONG).show();

// Populate list with our static array of titles in list in the
// Shakespeare class
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1,
Shakespeare.TITLES));

// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
// R.id.details relates to the res/layout-land/fragment_layout.xml
// This is first created when the phone is switched to landscape
// mode

View detailsFrame = getActivity().findViewById(R.id.details);

Toast.makeText(getActivity(), "detailsFrame " + detailsFrame,
Toast.LENGTH_LONG).show();

// Check that a view exists and is visible
// A view is visible (0) on the screen; the default value.
// It can also be invisible and hidden, as if the view had not been
// added.
//
mDualPane = detailsFrame != null
&& detailsFrame.getVisibility() == View.VISIBLE;

Toast.makeText(getActivity(), "mDualPane " + mDualPane,
Toast.LENGTH_LONG).show();

if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}

if (mDualPane) {
// In dual-pane mode, the list view highlights the selected
// item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
} else {
// We also highlight in uni-pane just for fun
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurCheckPosition, true);
}
}

管理方向翻转之间的状态该应用程序会跟踪当前选中的选择,因此当它恢复它时——在横向中再次返回它作为在 fragment 生命周期中使用 onSaveInstanceState() 突出显示的最后一个位置。该 fragment 保存其当前动态状态,因此稍后可以在其进程重新启动的新实例中重建。如果稍后需要创建 fragment 的新实例,则您在此处放置在 Bundle 中的数据将在提供给 onCreate(Bundle)、onCreateView(LayoutInflater, ViewGroup, Bundle) 和 onActivityCreated(Bundle) 的 Bundle 中可用。在代码中,新 fragment 恢复 onActivityCreated() 中的状态。这里的状态只是 mCurCheckPosition。

 @Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(getActivity(), "onSaveInstanceState",
Toast.LENGTH_LONG).show();

outState.putInt("curChoice", mCurCheckPosition);
}

FragmentManager 和 fragment 事务

帮助函数 (showDetails(position)) 显示所选项目的详细信息,通过在当前 UI 中就地显示 fragment ,或启动显示它的全新 Activity 。

 void showDetails(int index) {
mCurCheckPosition = index;

// The basic design is mutli-pane (landscape on the phone) allows us
// to display both fragments (titles and details) with in the same
// activity; that is FragmentLayout -- one activity with two
// fragments.
// Else, it's single-pane (portrait on the phone) and we fire
// another activity to render the details fragment - two activities
// each with its own fragment .
//
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
// We keep highlighted the current selection
getListView().setItemChecked(index, true);

// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment) getFragmentManager()
.findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.

details = DetailsFragment.newInstance(index);

Toast.makeText(getActivity(),
"showDetails dual-pane: create and replace fragment",
Toast.LENGTH_LONG).show();

// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}

} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
// That is: if this is a single-pane (e.g., portrait mode on a
// phone) then fire DetailsActivity to display the details
// fragment

// Create an intent for starting the DetailsActivity
Intent intent = new Intent();

// explicitly set the activity context and class
// associated with the intent (context, class)
intent.setClass(getActivity(), DetailsActivity.class);

// pass the current position
intent.putExtra("index", index);

startActivity(intent);
}
}

DetailsActivity:人像模式处理

如前所述,如果用户单击列表项并且当前布局不包含 R.id.details View (DetailsFragment 执行此操作),则应用程序启动 DetailsActivity Activity 以显示项目的内容。辅助函数在横向中创建一个新 fragment 以在纵向中绘制细节启动一个 Activity (DetailsActivity) 来管理细节 fragment ——即创建一个新的 DetailsFragment 并使用 FragmentManager 将其添加到 Root View ,如下所示。 DetailsActivity 嵌入 DetailsFragment 以在屏幕处于竖屏方向时显示选定的播放摘要:

//这是次要 Activity ,显示用户选择的内容//屏幕不够大,无法在一个 Activity 中显示所有内容。

公共(public)静态类 DetailsActivity 扩展 Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Toast.makeText(this, "DetailsActivity", Toast.LENGTH_SHORT).show();

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}

if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.

// create fragment
DetailsFragment details = new DetailsFragment();

// get and set the position input by user (i.e., "index")
// which is the construction arguments for this fragment
details.setArguments(getIntent().getExtras());

//
getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();
}
}

细节 fragment

首先创建 fragment 。 fragment 生命周期确保 onCreateView() 为 fragment 构建布局。它使用 TextView 构建 fragment -- text.setText(Shakespeare.DIALOGUE[getShownIndex()]) -- 并将其附加到滚动条 (ScrollView) 并返回(并呈现)绘制的 View 。

    // This is the secondary fragment, displaying the details of a particular
// item.

public static class DetailsFragment extends Fragment {

**snippet**

public int getShownIndex() {
return getArguments().getInt("index", 0);
}

// The system calls this when it's time for the fragment to draw its
// user interface for the first time. To draw a UI for your fragment,
// you must return a View from this method that is the root of your
// fragment's layout. You can return null if the fragment does not
// provide a UI.

// We create the UI with a scrollview and text and return a reference to
// the scoller which is then drawn to the screen

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

**snippet**

// programmatically create a scrollview and textview for the text in
// the container/fragment layout. Set up the properties and add the view

ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
.getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}

关于java - 如何横向并排显示 2 个 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838617/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com