【问题标题】:Android Custom Views vs inflating xmlAndroid 自定义视图与膨胀 xml
【发布时间】:2012-12-28 07:37:06
【问题描述】:

我有一个简单的问题:

您能给我一些关于使用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;
    }
}

抱歉,如果我打印的代码中有一些错误。它只是在这里没有拼写检查或语法检查。

【问题讨论】:

    标签: android android-custom-view layout-inflater


    【解决方案1】:

    我更喜欢第一种方式(自定义视图),因为这意味着所有的 findViewById() 操作都已经处理好了,让你的代码更整洁。

    根据你的例子:

    Shortcut shortcut = new Shortcut(this);
    shortcut.setBtnText("i'm btn");
    shortcut.setTitle("btn1");
    

    对我来说比:

    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");
    

    【讨论】:

      【解决方案2】:

      什么时候用哪个?

      只要你觉得它更适合你。

      它们有什么区别?

      什么都没有。并不真地。您在不同的类中运行相同的代码。

      为什么你会认为方法不同?

      唯一的区别在于shortcut class 你会有更多的模块化。您现在可以在任何您想要的活动中创建多个副本。但实际上它只是一种感觉更好的区别。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-05
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2012-08-27
        • 1970-01-01
        • 2012-05-16
        • 1970-01-01
        相关资源
        最近更新 更多