我为Spinner创建了一个如下所示的适配器:
public class MyAdapter extends ArrayAdapter<String> {
private LinearLayout llContainer;
public MyAdapter (Context context, List<String> names) {
super(context, 0, filters);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.some_layout, parent, false);
}
llContainer = (LinearLayout) convertView.findViewById(R.id.llContainer);
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
String name = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.some_layout_drop, parent, false);
}
Button button = (Button)convertView.findViewById(R.id.btn);
button.setText(name);
button.setOnClickListener(new OnClickListener(){
@Override
void onClick(View v){
addItemToLinearLayout();
}
})
return convertView;
}
private void addItemToLinearLayout(){
Button btn = new Button();
btn.setText("something");
btn.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.MATCH_PARENT,
));
//HERE I ADD A BUTTON TO THE LINEAR LAYOUT llContainer
llContainer.addView(btn);
}
}
问题是该按钮未显示在linearLayout中。在getView()方法中分配llContainer的事实是否与此有关?如果我通过/从XML中手动添加llContainer中的按钮,他就会显示出来。
澄清问题:我有一个微调视图。我想要的是当我点击它时,下拉列表中包含一些按钮。当我单击微调器视图上的其中一个按钮(显示用户选择的值的部分)时,添加按钮或textview等。如果我尝试调试应用程序,则llContainer包含添加的视图,但似乎mMeasuredHeight和mMeasuredWidth为0,并且id为0且coordonates为0。
答案 0 :(得分:0)
Button btn = new Button(); //without context?
可能像
Button btn = new Button(context); //pass context into the function
android.widget.Button中的:
Public Constructors
Button(Context context)
Button(Context context, AttributeSet attrs)
Button(Context context, AttributeSet attrs, int defStyleAttr)
Button(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)