LinearLayout WebView и кнопки - PullRequest
       40

LinearLayout WebView и кнопки

5 голосов
/ 26 марта 2010

Я недавно боролся с явно простой версией Android: я хотел WebView выше Button. Он работал нормально со следующими параметрами:

WebView:
  Height: wrap-content
  Weight: unset (by the way, what is the default?)

Button:
  Height: wrap-content
  Weight: unset

Однако, если веб-страница стала слишком большой, она выплеснулась на кнопку. Я пробовал разные комбинации веса и высоты, и все, кроме одной, либо полностью скрывали кнопку, либо частично закрывали ее. Это тот, который работает (скопировано с http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/res/layout/main.xml):

WebView:
  Height: 0
  Weight: 1

Button:
  Height: wrap-content
  Weight: unset

Если вы измените любой из них, например, придайте кнопке вес или измените высоту WebView на wrap-content, тогда она не будет работать. Мой вопрос: почему? Может кто-нибудь объяснить, что на Земле думает система макета Android?

Ответы [ 5 ]

2 голосов
/ 26 марта 2010

Что-то вроде следующего должно дать вам то, что вы хотите. Ключ - это layout_height = "fill_parent" и layout_weight = "1" для WebView.

<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <WebView android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />

        <Button android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
</LinearLayout>  


Редактировать : Упс, я неправильно понял ваш вопрос. Это layout_weight, который не дает перетекать кнопке (или тексту в вашем примере). Я не уверен, почему это происходит, но если в вашем LinearLayout есть один элемент "fill_parent", в дополнение к одному или нескольким элементам "wrap_content", вам нужно указать layout_weight для элемента "fill_parent", иначе потребуется над пространством для остальных виджетов.

1 голос
/ 19 августа 2014

Ну, я с тех пор понял это. Как работает система верстки Android:

  1. Все вещи выложены в соответствии с указанной высотой / шириной.
  2. Любой оставшийся вес распределяется между представлениями в соответствии с их весами.

(Очевидно, это никогда не объясняется.)

Поэтому, чтобы заставить его работать, вы хотите, чтобы кнопка была обернута содержимым, что делает ее настолько большой, насколько это необходимо, а веб-представление - нулевой высотой (поскольку она может уменьшаться до нуля). После шага 1 у вас будет правильная кнопка, а затем веб-просмотр нулевой высоты.

Затем вы устанавливаете вес кнопки на 0, а вес веб-просмотра на 1, так что любое оставшееся пространство отводится веб-обзору - то есть он расширяется, чтобы заполнить экран.

Имеет смысл, когда вы знаете алгоритм.

0 голосов
/ 18 августа 2014

Хорошо, вот код, чтобы сделать это:

WebView with Options Menu on Top and Bottom

На картинке выше есть 2 ряда кнопок: один сверху и один снизу. В середине находится WebView. Вот моя учетная запись GitHub, где вы можете скачать исходный код: https://github.com/GeneChuang1/Android/tree/Android

В противном случае, вот разбивка приложения:

Java-код (AndroidMobileAppSampleActivity.java):

package com.gene;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.gene.R;

public class AndroidMobileAppSampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_page);

        WebView mainWebView = (WebView) findViewById(R.id.webcontent);

        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mainWebView.setWebViewClient(new MyCustomWebViewClient());
        mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        mainWebView.loadUrl("http://www.google.com");
    }

    private class MyCustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

У меня есть 2 макета XML. Один для главной веб-страницы, другой представляет собой готовое меню, которое я на главной веб-странице. XML-формат «app_page.xml»:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:id="@+id/page_weekly_items_options_menu"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#d4dbe1"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/share"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedShare"></ImageView>

        <ImageView
            android:id="@+id/left_arrow"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedLeftArrow"></ImageView>

        <ImageView
            android:id="@+id/right_arrow"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedRightArrow"></ImageView>

        <ImageView
            android:id="@+id/notifications_pageweeklyitem"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedNotificationsPageWeeklyItem"></ImageView>

        <ImageView
            android:id="@+id/favorites_pageweeklyitem"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedFavoritesPageWeeklyItem"></ImageView>

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/webcontent_container"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@id/page_weekly_items_options_menu">

        <WebView
            android:id="@+id/webcontent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/menu"
            ></WebView>
        <include
            android:id="@+id/menu"
            layout="@layout/bottom_menu"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_alignParentBottom="true"
            android:gravity="bottom"
            android:layout_weight="1"
            />


    </RelativeLayout>

</RelativeLayout>

Другой формат XML - это bottom_menu.xml:

<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bottom_scroll_menu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom" >
    <!-- This layout is used by activity_main.xml.
    It is part of the main home page -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#17528c"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/Weekly"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedWeekly" >
        </ImageView>

        <ImageView
            android:id="@+id/Search"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedSearch" >
        </ImageView>

        <ImageView
            android:id="@+id/Favorites"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedFavorites" >
        </ImageView>

        <ImageView
            android:id="@+id/Notifications"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedNotifications" >
        </ImageView>

        <ImageView
            android:id="@+id/Profile"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedProfile" >
        </ImageView>

        <ImageView
            android:id="@+id/About"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedAbout" >
        </ImageView>
    </LinearLayout>

</HorizontalScrollView>

Манифест Android (только если кто-то забудет интернет-разрешение):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tscolari.mobile_sample"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidMobileAppSampleActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Опять же, вот моя учетная запись GitHub, где вы можете скачать исходный код: https://github.com/GeneChuang1/Android/tree/Android

-Гене Чуан

0 голосов
/ 09 октября 2012

Вы можете попробовать что-то вроде этого:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
    android:layout_height="match_parent" >

        <WebView
                android:id="@+id/wv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/btn" />

        <Button
            android:id="@+id/btn"
            android:layout_alignParentBottom="true" />
</RelativeLayout>
0 голосов
/ 11 марта 2011

вы можете указать высоту вашего webView в пикселях

android:layout_heigth = " 70px"

например

надеюсь, это поможет

...