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()
}
}
添加回答
舉報