3 回答
TA贡献2019条经验 获得超9个赞
这就是我最终的结果:
class DashboardFragment : Fragment() {
private lateinit var dashboardViewModel: DashboardViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
dashboardViewModel =
ViewModelProviders.of(this).get(DashboardViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_dashboard, container, false)
val textView: TextView = root.findViewById(R.id.text_dashboard)
dashboardViewModel.text.observe(this, Observer {
textView.text = it
})
val button2 : Button = root.findViewById<Button>(R.id.temporary_button2)
button2.setOnClickListener{
println("clicked button 2")
Toast.makeText(view?.context, "Button Clicked", Toast.LENGTH_LONG).show()
}
return root
}
}
TA贡献1772条经验 获得超5个赞
片段中没有findViewById,通常在片段内您应该重写该onCreateView方法,膨胀您自己的布局并尝试从您膨胀的视图中获取视图。例如 :
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (mContentView == null){
mContentView = inflater.inflate(R.layout.family_fragment_scene_list, container, false);
}
type = getArguments().getInt(ARGS_KEY_TYPE);
adapter = new SceneAdapter(getContext());
// get views from mContentView
mSceneList = (RecyclerView) mContentView.findViewById(R.id.swipe_target);
mSceneList.setLayoutManager(new LinearLayoutManager(getContext()));
mSceneList.setAdapter(adapter);
return mContentView;
}
TA贡献1963条经验 获得超6个赞
使用 getView()/view 尝试内部 onViewCreated 而不是 onCreateView。
例如。:
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
val temporary_button = getView().findViewById<Button>(R.id.temporary_button2)
temporary_button2.setOnClickListener{
makeText(this, "You clicked the button", LENGTH_LONG).show()
}
}
添加回答
举报