0

我有一个Fragment实例,我希望能够在片段加载并显示在屏幕上后实现单击侦听器和其他属性。我怎样才能做到这一点?我应该在哪里执行此操作?

4

1 回答 1

2

尝试以下操作:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.rap_prog_fields, container, false);
    TextView tv = (TextView) v.findViewById(R.id.text_view_1);
    Button b = (Button) v.findViewById(R.id.button);
    b.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             //do stuff
         }
     });
    //the rest of your views... in the same manner

    return v;
}

您还可以在返回后找到您的视图,onCreateView如下所示:

public void onStart() {
     super.onStart();
     Button b = (Button) getView().findViewById(R.id.button);
     b.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             //do stuff
         }
     });
     //Everything else...
 }

要在视图显示并在屏幕上完成操作后,您需要执行以下操作:

final ViewTreeObserver observer= button.getViewTreeObserver(); //you need an anchor view here that will be drawn via xml
       observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //do stuff here.....
    }
});
于 2013-07-30T14:24:15.083 回答