Android:访问Fragment类中的View对象

时间:2014-12-26 11:05:43

标签: java android gridview android-fragments view

如何从另一个方法访问在Fragment类的onCreateView方法中创建的View对象?我需要访问视图才能引用我的布局的Gridview控件。

public class comments_frag_activity extends Fragment{

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View android = inflater.inflate(R.layout.comments_frag, container, false);
}


 //other methods.....
 //other methods .....
 //other methods .....



 public void printTest()
   {
        if(!commentsGallery.isEmpty())
        {
            //I cant access the view object 'android'
            GridView list = (GridView)android.findViewById(R.id.commentinglist);
            CommentsAdapter bA = new CommentsAdapter(ctx, R.layout.comments_frag, commentsGallery);
            list.setAdapter(bA);
        }

}

5 个答案:

答案 0 :(得分:2)

将视图保存到类变量。


私人查看视图;
......
.....
@覆盖  onCreateView(LayoutInflater inflater,ViewGroup容器,Bundle savedInstanceState){    
    view = inflater.inflate(你的布局)

}

答案 1 :(得分:1)

全局声明它而不是局部变量

答案 2 :(得分:1)

Try This
public class comments_frag_activity extends Fragment{
private View android; 
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
      {
      android = inflater.inflate(R.layout.comments_frag, container, false);
      }


public void printTest()
        {
        if(!commentsGallery.isEmpty())
          {

          GridView list = (GridView)android.findViewById(R.id.commentinglist);
         CommentsAdapter bA = new CommentsAdapter(ctx, R.layout.comments_frag,              commentsGallery);
                list.setAdapter(bA);
            }
         } 

答案 3 :(得分:1)

在onViewCreated的onCreateView之后存储视图的引用:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    localGridView = (GridView) view.findViewById(R.id.commentinglist);
}

答案 4 :(得分:0)

如果您不想全局存储视图(出于某种原因),您可以随时执行类似

的操作
 public void printTest()
   {
        if(!commentsGallery.isEmpty())
        {
            //I cant access the view object 'android'
            GridView list = (GridView) getView().findViewById(R.id.commentinglist);
            CommentsAdapter bA = new CommentsAdapter(ctx, R.layout.comments_frag, commentsGallery);
            list.setAdapter(bA);
        }

}

getView()将返回onCreateView

中膨胀的根布局