私は Android 開発に不慣れで、同時に複数の webview を管理するための最良の方法を探しています。
私の目標は、開いた「タブ」をリストする小さなメニューを備えた単純な Web ブラウザーを作成し、レイアウト内のコンテンツ セクションをユーザーの選択に置き換えることです。Chrome やタブレットのストック ブラウザのようにタブを表示したくありません。
複数のビューを管理し、それらを切り替えて状態を維持する最良の方法は何ですか?
複数のフラグメント (それぞれに webview を含む) と FragmentManager を使用してコンテンツを置き換える必要がありますか? 選択した webview を削除および追加して、フレームレイアウトを手動で管理しますか?
更新:
今日は Fragment で遊んで、簡単なテスト プロジェクトを作成しました。ここにいくつかのコード: 私のレイアウト:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout android:id="@+id/fff"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>
</RelativeLayout>
マイ アクティビティ:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private WebFragment f1;
private WebFragment f2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
f1 = new WebFragment();
f2 = new WebFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fff, f1);
fragmentTransaction.commit();
f1.loadUrl("file:///android_asset/home.html");
f2.loadUrl("file:///android_asset/home.html");
}
private void switchFragment(int id) {
FragmentTransaction trx = getFragmentManager().beginTransaction();
if (id == 1) {
trx.replace(R.id.fff, f1);
} else if (id == 2) {
trx.replace(R.id.fff, f2);
}
trx.commit();
}
...
}
私のフラグメント:
<?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="vertical" >
<WebView android:id="@+id/ww"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
public class WebFragment extends Fragment {
private static final String TAG = "WebFragment";
private View v = null;
private WebView ww;
private String url = null;;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "WebFragment onCreateView");
if (v == null) {
v = inflater.inflate(R.layout.test_layout, container, false);
this.ww = (WebView) v.findViewById(R.id.ww);
// WebView settings here...
this.ww.setWebViewClient(new WebViewClient());
if (this.url != null)
this.ww.loadUrl(url);
}
return v;
}
public void loadUrl(String url) {
this.url = url;
if (this.ww != null)
this.ww.loadUrl(url);
}
}
アクティビティのメニューを使用して、いずれかのフラグメントに切り替えることができます。明らかに、フラグメントを管理するためのある種のコントローラーと、アクティビティのイベントを設定するための「ブリッジ」が必要になりますが、問題ないようです。
そのような複数のフラグメント (それぞれに webview が含まれる) をメモリに保持しても問題ありませんか? WebView とそのコンテンツを保持する必要がありますが、この場合、フラグメントはコンテナーとしてのみ使用されます。
まだいくつかのコメントや提案を受け付けています。
ご協力いただきありがとうございます。