【问题标题】:The method findViewById(int) is undefined for the type PostDetail (Fragment)对于 PostDetail (Fragment) 类型,方法 findViewById(int) 未定义
【发布时间】:2014-06-13 11:07:31
【问题描述】:

我在 ArticleActivity(活动)中有代码

尝试实现 PostDetail (Fragment) findViewById(R.id.like).setOnClickListener(new ResultLikeListener(this,(TextView)findViewById(R.id.like), res));

请你帮帮我。

public class PostDetail extends Fragment{

    private int mId;
    TextView mTitle;
    WebView mWebView;
//  TextView mBody;



     private Tracker tracker;

        @Override
        public void onCreate(final Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

        }





    }



.............
}

【问题讨论】:

  • 片段的 onCreateView() 中是否有任何 rootView.. 使用该 rootview.findViewById() 来获取视图。

标签: java android android-fragments


【解决方案1】:

您必须@overide Fragment 的 OnCrateView 方法来获取您的小部件的 id,如 textview 或 edittext,无论您想要什么。在 oncreate 视图中,您必须像在活动中一样膨胀您的布局,因为您设置 setcontentview,但在片段中您必须膨胀您的布局视图。代码类似于:

 public class PostDetail extends Fragment {
   TextView mTitle;
    @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View view = (ViewGroup) inflater.inflate(R.layout.YOUR_LAYOUT_VIEW,   null);
        mTitle= (TextView ) _view.findViewById(R.id.YOUR_TEXTVIEW_ID);
       return view;
     }

}

【讨论】:

  • 不是 View view = inflater.inflate(R.layout.YOUR_LAYOUT_VIEW, container, false); ?
【解决方案2】:

你需要像这样使用它:

View rootView = inflater.inflate(R.layout.article_fragnment, this, false);
TextView txtView = rootView.findViewById(R.id.like).setOnClickListener( new ResultLikeListener( this,(TextView)findViewById(R.id.like), res ));

【讨论】:

    【解决方案3】:

    你需要从它的onCreate函数中获取fragment的rootView。

    rootView.findViewById(R.id.like).setOnClickListener( new ResultLikeListener( this,(TextView)findViewById(R.id.like), res ));
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多