2016-01-17 2 views
0

Я создал два вида таможни: один расширён от SwipeRefreshLayout (имя: ColorSwipeRefreshLayout), а другой расширен от RecyclerView (Name: ColorRecyclerView).Как создать пользовательский вид в пользовательском представлении в Android?

Я просто хочу включить ColorRecyclerView в ColorSwipeRefreshLayout и, наконец, включить ColorSwipeRefreshLayout в свой фрагмент. Но каждый раз, когда я хочу назвать мою ColorRecyclerView в моем Fragment классе, получил NullPointerException на объекте и не понимаю, почему ...

Существует код:

ColorRecyclerView.java

public class ColorRecyclerView extends RecyclerView { 
final static int COLUMN_COUNT = 3; 
RecyclerView.LayoutManager layoutManager; 
RVColorAdapter adapter; 
List<HueColor> colors; 
ApiHelper apiHelper; 

public ColorRecyclerView(Context context) { 
    super(context); 
    initializeView(context); 
} 

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

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

public void setHelper(ApiHelper apiHelper) { 
    this.apiHelper = apiHelper; 
} 

public void update(List<HueColor> colors) { 
    this.colors = colors; 
    adapter = new RVColorAdapter(apiHelper,colors); 
    setAdapter(adapter); 
} 

private void initializeView(Context context) { 
    layoutManager = new GridLayoutManager(context,COLUMN_COUNT); 
    setLayoutManager(layoutManager); 
} 

colorrecyclerview.xml

<android.support.v7.widget.RecyclerView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

ColorSwip eRefreshLayout.java

public class ColorSwipeRefreshLayout extends SwipeRefreshLayout { 
ColorRecyclerView colorRecyclerView; 

public ColorSwipeRefreshLayout(Context context) { 
    super(context); 
    initializeView(context); 
} 

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

private void initializeView(Context context) { 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View v = inflater.inflate(R.layout.swiperefreshlayout_color, this, true); 
    colorRecyclerView = (ColorRecyclerView) v.findViewById(R.id.colorRecyclerView); 

    setColorSchemeResources(R.color.color_scheme_1_1, R.color.color_scheme_1_2, 
      R.color.color_scheme_1_3, R.color.color_scheme_1_4); 

} 

public ColorRecyclerView getColorRecyclerView() { 
    return this.colorRecyclerView; 
} 

colorswiperefreshlayout.xml

<android.support.v4.widget.SwipeRefreshLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <com.color.hue.ui.view.ColorRecyclerView 
     android:id="@+id/colorRecyclerView" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 


ColorFragment.java

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    // ...code... 
    View view = inflater.inflate(R.layout.fragment_color, container, false); 
    ButterKnife.bind(this, view); 

    mRecyclerView = mSwipeRefreshLayout.getColorRecyclerView(); 
    mRecyclerView.setHelper(mApiHelper); // Got NullPointerEx here 

    // ...code... 
    return view; 
} 

colorfragment.xml

<com.color.hue.ui.view.ColorSwipeRefreshLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/colorSwipeRefreshLayout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

Спасибо :)


EDIT: Я добавил инфляцию в initializeView из ColorSwipeRefreshLayout и он работает :)

+0

Накачайте 'colorswiperefreshlayout.xml' в вашем фрагменте –

+0

Это решение, спасибо;) –

ответ

0

Ваш SwipeRefreshLayout не должен вызывать initializeView в конструктор.

Поскольку вы раздуваете его в своем фрагменте из макета, к моменту создания конструктора пока нет комментариев. Таким образом,

colorRecyclerView = (ColorRecyclerView) findViewById(R.id.colorRecyclerView);` 

не обнаружит ресайклеров.

Вариант будет состоять в том, чтобы раздуть/создать recyclerview в вашем методе initializeView или просто искать ссылку позже.

Хорошим моментом для вашей интериации, вероятно, будет onFinishInflate.

+0

Спасибо, она работает с инфляцией в initializeView + переопределяя onFinishInflate :) Но ColorSwipeRefreshLayout сделать бесконечную загрузку, когда onRefresh срабатывает, в то время как SwipeRefreshLayout работает правильно ... Не переопределил метод, понял идею? –

+0

@ julian-l грустно, есть много проблем с индикатором загрузки, многие решения можно найти здесь. Кроме того, не могли бы вы принять ответ, если он сработает? благодаря –

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

  • Нет связанных вопросов^_^