我有自定义视图扩展RelativeLayout
,我想在其中添加RecyclerView
。但是无法显示recyclerView。
如何解决?谢谢!
代码:
LineChart.java
public class LineChart extends RelativeLayout {
RecyclerView mRecyclerView;
public LineChart(Context context) {
super(context);
init(context, null);
}
public LineChart(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public LineChart(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
protected void init(Context context, @Nullable AttributeSet attrs) {
setWillNotDraw(false);
initInside();
}
protected void initInside() {
View v = inflate(getContext(), R.layout.line_chart_recyclerview, null);
LineChart.LayoutParams params = new LineChart.LayoutParams(
getWidth() / 2, getHeight());
params.addRule(LineChart.ALIGN_PARENT_RIGHT);
addView(v, params);
mRecyclerView = (RecyclerView) findViewById(R.id.lineChartRecyclerView);
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
list.add("~~~");
LineChartAdapter lineChartAdapter = new LineChartAdapter(getContext(),
list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(lineChartAdapter);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
LineChartAdapter.java
public class LineChartAdapter
extends RecyclerView.Adapter<LineChartViewHolder> {
private List<String> mList;
private Context mContext;
public LineChartAdapter(Context context, List<String> list) {
this.mContext = context;
this.mList = list;
}
@Override
public LineChartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext)
.inflate(R.layout.item_line_chart, parent,
false);
return new LineChartViewHolder(itemView);
}
@Override
public void onBindViewHolder(LineChartViewHolder holder, int position) {
holder.mTextView.setText(String.valueOf(position));
}
@Override public int getItemCount() {
return mList == null ? 0 : mList.size();
}
}
LineChartViewHolder.java
public class LineChartViewHolder extends RecyclerView.ViewHolder {
protected TextView mTextView;
public LineChartViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(
R.id.text1024);
}
}
答案 0 :(得分:1)
我想,我知道原因。
View v = inflate(getContext(), R.layout.line_chart_recyclerview, null);
LineChart.LayoutParams params = new LineChart.LayoutParams(
getWidth() / 2, getHeight());
params.addRule(LineChart.ALIGN_PARENT_RIGHT);
addView(v, params);
此处,getWidth()
和getHeigth()
仍为0.因此您的视图将具有(0; 0)大小
为了解决这个问题,我建议用
LayoutInflater.from(context).inflate(R.layout.line_chart_recyclerview, this);
如果有帮助,请告诉我。