2015-06-25 2 views
2

Я использую GifWebView данный hereРасширение пользовательского класса компоновки - конструктор никогда не использовал

Я знаю, основной вид деятельности и т.д. работает отлично, как я проверил его перед внедрением в XML для макета кадра. Но теперь, когда я использую Frame Layout, я сталкиваюсь с проблемами.

Я просто предоставить вам мой код и краткое объяснение:

XML

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

    <com.example.dencallanan.giftestapp.GifWebView 
     android:id="@+id/GWebView" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 

     /> 

    <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" android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin" 
     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 

     <EditText 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/editText" 
      android:layout_marginBottom="153dp" 
      android:layout_alignParentBottom="true" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentEnd="true" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" 
      android:hint="USERNAME" /> 

     <EditText 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/editText2" 
      android:layout_marginTop="58dp" 
      android:layout_alignTop="@+id/editText" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentEnd="true" 
      android:layout_alignLeft="@+id/editText" 
      android:layout_alignStart="@+id/editText" 
      android:hint="PASSWORD" /> 

     <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Log In" 
      android:id="@+id/button" 
      android:layout_below="@+id/editText2" 
      android:layout_centerHorizontal="true" 
      android:layout_marginTop="25dp" /> 
    </RelativeLayout> 


</FrameLayout> 

GifWebView

public class GifWebView extends WebView { 

    public GifWebView(Context context, String path) { 

     super(context); 
     loadUrl(path); 
    } 

    public GifWebView(Context context, AttributeSet attrs, String path) { 

     super(context, attrs); 

    } 

    public GifWebView(Context context, AttributeSet attrs, int defStyle, String path) { 

     super(context, attrs, defStyle); 

    } 
} 

Я думаю, что моя проблема лежит здесь. Я видел онлайн, что я должен добавить два других метода конструктора, рассмотренных выше. Но кажется, что первый из них используется только один, т. Е. Два вторых конструктора дают предупреждение methods never used.

Возможно, я ошибаюсь, но, возможно, вам нужны эти конструкторы для реализации класса макета в XML, и эти конструкторы никогда не используются ... почему?

Следующие две строки находятся в моей MainActivity, чтобы помочь вам понять, что происходит.

gWView = (GifWebView) findViewById(R.id.GWebView); 
    gWView = new GifWebView(this, "file:///android_asset/watg.gif"); 

Я бы очень признателен за любую помощь, данную проблему был у меня часами.

Проблема

Ничто не показывает на экране Android ... просто пустой

редактирования.К Blackbelt

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:myapp="http://schemas.android.com/apk/res-auto" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 

    <com.example.dencallanan.giftestapp.GifWebView 
     android:id="@+id/GWebView" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     myapp:fpath="watg" <!-- also tried "watg.gif" --> 

     /> 

    <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" android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin" 
     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 

     <EditText 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/editText" 
      android:layout_marginBottom="153dp" 
      android:layout_alignParentBottom="true" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentEnd="true" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" 
      android:hint="USERNAME" /> 

     <EditText 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/editText2" 
      android:layout_marginTop="58dp" 
      android:layout_alignTop="@+id/editText" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentEnd="true" 
      android:layout_alignLeft="@+id/editText" 
      android:layout_alignStart="@+id/editText" 
      android:hint="PASSWORD" /> 

     <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Log In" 
      android:id="@+id/button" 
      android:layout_below="@+id/editText2" 
      android:layout_centerHorizontal="true" 
      android:layout_marginTop="25dp" /> 
    </RelativeLayout> 


</FrameLayout> 

attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="GifWebView"> 
     <attr name="fpath" format="string" /> 
    </declare-styleable> 
</resources> 

GifWebView.java

public class GifWebView extends WebView { 

    public GifWebView(Context context) { 

     super(context); 
    } 

    public GifWebView(Context context, AttributeSet attrs) { 

     super(context, attrs); 

     TypedArray a = context.obtainStyledAttributes(attrs, 
       R.styleable.GifWebView); 
     CharSequence s = a.getString(R.styleable.GifWebView_fpath); 
     loadUrl(s.toString()); 
    } 

    public GifWebView(Context context, AttributeSet attrs, int defStyle) { 

     super(context, attrs, defStyle); 

     TypedArray a = context.obtainStyledAttributes(attrs, 
       R.styleable.GifWebView); 
     CharSequence s = a.getString(R.styleable.GifWebView_fpath); 
     loadUrl(s.toString()); 
    } 
}  

ответ

5

вы не должны перегружать конструктор вида. Используйте

public GifWebView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
} 

и

public GifWebView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
} 

и обеспечить не-по-умолчанию, параметры, программно или определить пользовательский атрибут для пользовательских View

+0

Спасибо за ответ, не могли бы вы расширить этот маленький кусочек , предположим, я знаю очень мало, поскольку я всего лишь новичок. Что вы подразумеваете под «параметрами не по умолчанию» или «настраиваемым атрибутом для моего пользовательского« представления »? Это исправить мою проблему или это просто хорошая привычка? Должны ли использоваться эти методы конструктора? Почему не мои? –

+0

Хорошо, я думаю, что получаю то, что вы говорите. Поэтому я создаю файл 'attrs.xml' в папке значений. Затем я создаю новый макет. Я использую этот макет в основном файле xml, и я могу добавить стиль и пользовательские атрибуты. Затем я получаю доступ к этим атрибутам из класса. У меня есть 2 вопроса. Как указать, что новый макет соответствует GifWebView? И я сохраняю все 3 конструктора и ставил метод loadURL() во всех них. Большое спасибо за то, что вы терпеливы, я буду над луной, если это будет работать. –

+0

О, я понял первый вопрос, но понятия не имею о втором. –

Смежные вопросы