创建 Fragment 并设置视图元素
Create Fragment and set view elements
我正在创建一个新的 Fragment 并想设置一些视图元素属性。这是我尝试的:
new DefaultSlide()
.setImage(R.drawable.logo)
.setTitle("blabla")
.setText("fubar"));
这是我的 DefualtSlide:
public class DefaultSlide extends SlideFragment {
@BindView(R.id.defaultImage)
ImageView defImage;
@BindView(R.id.defaultTitle)
TextView title;
@BindView(R.id.defaultText)
TextView text;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_default_slide, container, false);
ButterKnife.bind(this, view);
return view;
}
public DefaultSlide setImage(int image) {
defImage.setImageResource(image);
return this;
}
public DefaultSlide setTitle(String title) {
this.title.setText(title);
return this;
}
public DefaultSlide setText(String text) {
this.text.setText(text);
return this;
}
@Override
public int backgroundColor() {
return R.color.backgroundColor;
}
@Override
public int buttonsColor() {
return R.color.colorPrimary;
}
}
问题是,我得到一个空指针异常。我的猜测是视图元素尚不可见,因此我无法访问它们。是否有关于如何在创建片段时设置视图属性的最佳实践?
您必须在 bundle 中传递值并在 onCreateView 中访问它们,并通过传递这些值来调用相关方法。
我正在创建一个新的 Fragment 并想设置一些视图元素属性。这是我尝试的:
new DefaultSlide()
.setImage(R.drawable.logo)
.setTitle("blabla")
.setText("fubar"));
这是我的 DefualtSlide:
public class DefaultSlide extends SlideFragment {
@BindView(R.id.defaultImage)
ImageView defImage;
@BindView(R.id.defaultTitle)
TextView title;
@BindView(R.id.defaultText)
TextView text;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_default_slide, container, false);
ButterKnife.bind(this, view);
return view;
}
public DefaultSlide setImage(int image) {
defImage.setImageResource(image);
return this;
}
public DefaultSlide setTitle(String title) {
this.title.setText(title);
return this;
}
public DefaultSlide setText(String text) {
this.text.setText(text);
return this;
}
@Override
public int backgroundColor() {
return R.color.backgroundColor;
}
@Override
public int buttonsColor() {
return R.color.colorPrimary;
}
}
问题是,我得到一个空指针异常。我的猜测是视图元素尚不可见,因此我无法访问它们。是否有关于如何在创建片段时设置视图属性的最佳实践?
您必须在 bundle 中传递值并在 onCreateView 中访问它们,并通过传递这些值来调用相关方法。