在片段中添加按钮? [复制]
Posted
技术标签:
【中文标题】在片段中添加按钮? [复制]【英文标题】:adding a button in a fragment? [duplicate] 【发布时间】:2016-11-30 04:01:33 【问题描述】:我正在尝试向我的片段布局添加一个按钮,但它说方法 findViewByid
无法解析。我在片段中的onCreateView
方法中实现它。为什么会出现这个错误?
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.Button;
public class extra extends Fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
Button myButton = (Button) findViewById(R.id.my_button);
return inflater.inflate(R.layout.extra, container, false);
【问题讨论】:
因为你的类没有 findByViewId 方法 检查我的解决方案@asdddd 【参考方案1】:使用我的代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View view = inflater.inflate(R.layout.extra, container, false);
Button myButton = (Button)view.findViewById(R.id.my_button);
return view;
【讨论】:
【参考方案2】:public class extra extends Fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
// Inflate the layout for this fragment
View v = LayoutInflater.from(getActivity()).inflate(
R.layout.YOUR_LAYOUT, null);
Button myButton = (Button) v.findViewById(R.id.my_button);
return v;
使用上面的代码
【讨论】:
【参考方案3】:您需要使用View
。喜欢,
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View rootView = inflater.inflate(R.layout.extra, container, false);
// Inflate the layout for this fragment
Button myButton = (Button) rootView.findViewById(R.id.my_button);
return rootView;
【讨论】:
【参考方案4】:使用此代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View rootView = inflater.inflate(R.layout.extra, container, false);
Button myButton = (Button) rootView.findViewById(R.id.my_button);
return rootView;
【讨论】:
以上是关于在片段中添加按钮? [复制]的主要内容,如果未能解决你的问题,请参考以下文章