0

簡単な質問があります:

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;
    }
}

申し訳ありませんが、コードに誤りがある場合は印刷しました。スペルチェックや構文チェックなしでここにあります。

4

2 に答える 2

3

I prefer the first way (custom views), because it means all the findViewById() operations are already taken care of, making your code a little neater.

As per your example:

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

is to me a lot tidier than:

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");
于 2013-10-24T07:55:46.970 に答える
0

When to use which?

Whenever you feel it suits you better.

What's the difference between them?

Nothing. Not really. You are running the same code in a different Class.

Why would you think the method is different?

The only difference is in shortcut class you'd have a little more modularity. You can now create several copies in whatever activity you want. But really its just a What feels better difference.

于 2012-12-28T07:49:31.887 に答える