您好,我是 android(也是 java)的新手,所以我尝试创建一些简单的应用程序。这个应用程序将有一个来自 xml 的基本布局和一个从代码创建并插入到该基本布局中的动态布局。但是当我使用 findViewbyId 时它不起作用,它返回为空。
之后我尝试在尝试 findViewbyId 之前插入“setContentView”并清理项目......它仍然得到 NULL ..这是我的代码..
package com.app.something;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
LinearLayout lLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
GridLayout grid = new GridLayout(this);
grid.setColumnCount(5);
for (int i = 0;i<20;i++){
ImageButton ib = new ImageButton(this);
ib.setImageResource(R.drawable.ic_launcher);
ib.setId(i+1);
final int index = i;
ib.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("TAG","The index is" + index);
}
});
grid.addView(ib);
}
lLayout = (LinearLayout)findViewById(R.layout.activity_main);
if(lLayout == null)Log.i("TAG", "It said, NULLL");
else {
lLayout.addView(grid);
setContentView(lLayout);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
这是基本布局activity_main(空白)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#ffffff00"
tools:context=".MainActivity" >
</RelativeLayout>