我在 drawable-mdpi 文件夹中有一个名为 c1.png 的图像。我想用 Java 把它放到布局中:
package ...;
import android.os.Bundle;
//import android.provider.MediaStore.Images;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout)findViewById(getCurrentFocus().getId() );
ImageView img = new ImageView(this);
ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
img.setLayoutParams(lp);
img.setImageDrawable(getResources().getDrawable(R.drawable.c1));
layout.addView(img);
setContentView(layout);//Doesn't matter, if it's commented or not. The error still exists.
}
@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;
}
}
启动时我得到:“不幸的是,%application_name 已停止”。我看到很多例子,在 id 参数中使用 R.id.*,但它也停止了(比如 R.id.linearLayout1),或者 R 没有这样的常量(比如 R.id.c1)。我怎样才能做到这一点?