为什么我有mainLayout==null
?
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
LinearLayout mainLayout = FindViewById<LinearLayout> (Resource.Layout.Main);//return null
mainLayout.Touch+=(s,e)=>
{
//something
}
}
如何获取MainLayout或添加事件处理程序如何触摸?
Resource.designer.cs :
public partial class Layout
{
public const int Main = 2130903041;
//other
}
答案 0 :(得分:5)
LinearLayout mainLayout = FindViewById<LinearLayout>
(Resource.Layout.Main);//return null
您使用布局文件作为参数:Resource.Layout.Main
您应该使用的是您在id
内分配给LinearLayout的Resource.Layout.Main
。
尝试:
LinearLayout mainLayout = FindViewById<LinearLayout>
(Resource.Id.linear_layout_id);
答案 1 :(得分:5)
在XML上设置一个ID(android:id =“@ + id / mainLayoutID”),其中包含名为“mainLayout”的LinearLayout。
然后:
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Your layout reference
final LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayoutID);
}