我有一个简单的问题:
你能给我一些关于Custom views vs Layout inflater
在执行代码中使用的提示吗?哪个更喜欢使用?谁能解释一下两者的优缺点。
如果我的问题不清楚,下面是一个解释的例子。像这样声明它:
public class Shortcut extends RelativeLayout{
private Button btn;
private TextView title;
/*some getters & setters here*/
public Shortcut(Context context){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.shortcut, /*other params*/);
title = v.findViewById(R.id.title);
btn = v.findViewById(R.id.btn);
}
}
并像这样使用它
public class MainActivit extends Activity{
ListView list = new ListView();
public void onCreate(Bundle...){
......
list.setAdapter(new MyAdapter());
}
// some code here
private class MyAdapter extends BaseAdapter{
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Shortcut shortcut = new Shortcut(this);
shortcut.setBtnText("i'm btn");
shortcut.setTitle("btn1");
return shortcut;
}
}
或者这样做:
public class MainActivit extends Activity{
ListView list = new ListView();
public void onCreate(Bundle...){
......
list.setAdapter(new MyAdapter());
}
// some code here
private class MyAdapter extends BaseAdapter{
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.shortcut, parent, false);
}
TextView title = (TextView) view.findViewById(R.id.title);
Button btn = (Button) view.findViewById(R.id.btn);
title.setText("Hey!");
btn.setText("smth");
return view;
}
}
抱歉,如果我打印的代码中有一些错误。它只是在这里没有拼写检查或语法检查。