我正在开发一款与典型新闻阅读器应用非常相似的应用。我在屏幕左侧的片段中有一个Listview,如果我们在横向视图中,则右侧显示所选项目的详细信息。否则,细节片段将显示在其自己的Activity中。我的工作很好。
然而,有一点需要注意:我只希望它在更大的屏幕尺寸上表现得这样(可能只有平板电脑,但这可能会发生变化)。在较小的设备上,我想只看到Listview片段,并在其自己的活动中启动细节片段,无论方向如何。我也有这个工作。
我目前遇到的问题是详细活动以及如何确定何时完成()并返回上一个活动以并排显示片段。我有以下代码适用于较大的设备,但不允许较小的设备查看此活动,因此详细信息片段:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
如何确定返回上一个活动将允许片段并排显示?
答案 0 :(得分:3)
尤里卡!我的解决方案是为空活动的详细信息活动提供备用布局。在我给布局充气之后,我可以检查一下我期待的片段是否在布局中,如果不是,那么我就完成了()。
/ res / layout中的details_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:name="com.website.DetailsFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/details_fragment"
android:layout_weight="75">
</fragment>
</LinearLayout>
details_view.xml 这个适用于任何屏幕尺寸,您不希望在横向模式下显示其自己的活动中的详细信息片段(在我的情况下,或多或少的平板电脑)。
<?xml version="1.0" encoding="utf-8"?>
<!-- Note: This file has an empty layout to notify
DetailsViewActivity that we should go back to landscape
and view the fragments side by side -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
</LinearLayout>
只需将空的details_view.xml文件放在任何布局目录中,该目录中的布局文件允许并排显示片段。
如果我们想要并行返回,那么要退出DetailsViewActivity的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_view);
mDetailsView = (TopicViewFragment)getSupportFragmentManager()
.findFragmentById(R.id.details_fragment);
// We can handle the fragments side by side in the previous activity
// so lets go back there
if ((mDetailsView == null || !mDetailsView.isInLayout()) &&
getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
我本来希望少一些数据重复,但这个解决方案还不错。它只强制您将一个额外的布局文件复制到并行片段布局文件所在的同一目录中。真的不错。
答案 1 :(得分:1)
我认为以下也可以在没有使用空布局的情况下工作。
package de.vogella.android.fragments;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.TextView;
public class DetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Need to check if Activity has been switched to landscape mode
// If yes, finished and go back to the start Activity
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
setContentView(R.layout.details_activity_layout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String s = extras.getString("value");
TextView view = (TextView) findViewById(R.id.detailsText);
view.setText(s);
}
}
}