2016-10-12 2 views
0

Я использую retrofit и coordinatorlayout. Кажется, все работает нормально, но я получаю небольшую проблему. Я хочу, чтобы макет отображался в тот момент, когда ответ был успешным. По этой причине я вызываю setContentView внутри ответа (я не знаю, хорошо это или нет)setContentView при успешном отклике ответа не отображает всю информацию в прокрутке?

Моя проблема в том, что это работает, но макет не выполняет прокрутку во всех информация. Он перерезал последние строки текста. Если я вызову setContentView в методе oncreate, прокрутка в координаторе будет выполнена (показать всю информацию), но в этом сценарии я могу увидеть дизайн макета перед всеми правильными изображениями и текстом, когда закончите успешную реакцию.

Кто-нибудь знает, как я могу исправить эту проблему ??

Спасибо заранее

Деталь Класс:

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     apiCall(R.layout.detail); 
    } 

    private void apiCall(final int layout){ 
     Bundle extras = getIntent().getExtras(); 
     if (extras != null) { 
      id = extras.getString("id"); 
     } 

     ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); 

     Call<Hostel> call = apiService.getHostelId(id); 
     call.enqueue(new Callback<Hostel>() { 
      @Override 
      public void onResponse(Call<Hostel> call, Response<Hostel> response) { 

       try { 
        if (response.code() == 200) { 
         setContentView(layout); 
         initView(response); 
         setToolbar(); 
        } else { 
         Toast.makeText(getApplication(), getResources().getString(R.string.no_conexion), Toast.LENGTH_SHORT).show(); 
        } 
       }catch (Exception e){ 
        Log.e(TAG, e.toString()); 
       } 
      } 
      @Override 
      public void onFailure(Call<Hostel> call, Throwable t) { 
       Log.e(TAG, t.toString()); 
      } 
     }); 
    } 

detail.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/coordinator" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true"> 

    <android.support.v4.widget.NestedScrollView 
     android:id="@+id/scroll" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_below="@+id/app_bar" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:orientation="vertical" 
      android:paddingTop="24dp"> 

      <android.support.v7.widget.CardView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_margin="19dp"> 
       <LinearLayout 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:orientation="vertical" 
        android:padding="5dp"> 
        <LinearLayout 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:orientation="vertical" 
         android:paddingLeft="10dp" 
         android:paddingBottom="10dp" 
         android:paddingTop="5dp"> 
         <TextView 
          android:id="@+id/propertyName_detail" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:text="@string/description" 
          android:textAppearance="@style/TextAppearance.AppCompat.Title" /> 
         <TextView 
          android:id="@+id/description_detail" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          /> 
        </LinearLayout> 
       </LinearLayout> 
      </android.support.v7.widget.CardView> 

      <android.support.v7.widget.CardView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_marginBottom="19dp" 
       android:layout_marginLeft="19dp" 
       android:layout_marginRight="19dp"> 
       <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:orientation="vertical"> 
        <LinearLayout 
         style="@style/Widget.CardContent" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:orientation="horizontal"> 
         <TextView 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:text="@string/address_1" 
          android:textAppearance="@style/TextAppearance.AppCompat.Title" /> 
         <TextView 
          android:id="@+id/addres_one_detail" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"/> 
        </LinearLayout> 
        <LinearLayout 
         style="@style/Widget.CardContent" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:orientation="horizontal"> 
         <TextView 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:text="@string/address_2" 
          android:textAppearance="@style/TextAppearance.AppCompat.Title" /> 
         <TextView 
          android:id="@+id/addres_two_detail" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"/> 
        </LinearLayout> 
        <LinearLayout 
         style="@style/Widget.CardContent" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:orientation="horizontal"> 
         <TextView 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:text="@string/city" 
          android:textAppearance="@style/TextAppearance.AppCompat.Title" /> 
         <TextView 
          android:id="@+id/city_detail" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"/> 
        </LinearLayout> 
        <LinearLayout 
         style="@style/Widget.CardContent" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:orientation="horizontal"> 
         <TextView 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:text="@string/county" 
          android:textAppearance="@style/TextAppearance.AppCompat.Title" /> 
         <TextView 
          android:id="@+id/country_detail" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content"/> 
        </LinearLayout> 
       </LinearLayout> 

      </android.support.v7.widget.CardView> 

      <android.support.v7.widget.CardView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_margin="19dp"> 
       <LinearLayout 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:orientation="vertical" 
        android:padding="5dp"> 

        <TextView 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:text="@string/directions" 
         android:textAppearance="@style/TextAppearance.AppCompat.Title" /> 
        <TextView 
         android:id="@+id/directions_detail" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content"/> 
       </LinearLayout> 
      </android.support.v7.widget.CardView> 
     </LinearLayout> 

    </android.support.v4.widget.NestedScrollView> 

    <android.support.design.widget.AppBarLayout 
     android:id="@+id/app_bar" 
     android:layout_width="match_parent" 
     android:layout_height="256dp" 
     android:fitsSystemWindows="true" 
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> 

     <android.support.design.widget.CollapsingToolbarLayout 
      android:id="@+id/collapser" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:fitsSystemWindows="true" 
      app:contentScrim="?attr/colorPrimary" 
      app:expandedTitleMarginEnd="64dp" 
      app:expandedTitleMarginStart="48dp" 
      app:layout_scrollFlags="scroll|exitUntilCollapsed"> 

      <ImageView 
       android:id="@+id/image_detail" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:fitsSystemWindows="true" 
       android:scaleType="centerCrop" 
       app:layout_collapseMode="parallax" /> 

      <android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto" 
       android:id="@+id/toolbar" 
       android:layout_width="match_parent" 
       android:layout_height="?attr/actionBarSize" 
       android:background="@android:color/transparent" 
       app:layout_collapseMode="pin" 
       app:popupTheme="@style/ThemeOverlay.AppCompat.Light" 
       app:theme="@style/CustomActionBar" 
       /> 
     </android.support.design.widget.CollapsingToolbarLayout> 
    </android.support.design.widget.AppBarLayout> 
</android.support.design.widget.CoordinatorLayout> 

ответ

1

Зова setContentView в oncreate просто попробовать сделать шоу макета для пользователя, когда ответ является успешным. Вы можете управлять им с помощью alpha свойства widget

андроида: альфа = «0,0», чтобы сделать вид невидимого

андроида: альфа = «1,0», чтобы сделать вид видимой

сейчас oncreate вызов

CoordinatorLayout cL=(CoordinatorLayout)findViewById(R.id.coordinator); 
cL.setAlpha(0); 

и после получения ответа преуспевающим сделать его visible например:

cL.setAlpha(1); 
0

Я хотел бы предложить, чтобы сделать setContentView(your_layout) на onCreate(), как это хорошая практика, чтобы следовать.

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

progressBar.setVisibility(View.GONE); 

Это является распространенным решением в использовании компонентов на основе собственных андроидов.

В противном случае вы можете установить видимость прокрутки (id = scroll с вашего кода) в начале GONE. Затем просто установите видимость снова, когда данные поступают успешно. Что-то вроде:

@Override 
public void onResponse(Call<Hostel> call, Response<Hostel> response) { 
    try { 
     if (response.code() == 200) { 
     yourScrollView.setVisibility(View.VISIBLE); 
     // Do the rest of the your implementation here; 

    } catch (Exception e) { 
    // Blah blah 
    } 
}