gpt4 book ai didi

java - 如何用java在布局中放置图像?安卓

转载 作者:行者123 更新时间:2023-12-02 07:13:27 25 4
gpt4 key购买 nike

我在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)。我怎样才能做到这一点?

最佳答案

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(R.id.layoutID ); // //layoutID is id of the linearLayout that defined in your main.xml file

ImageView img = new ImageView(this);
ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
img.setLayoutParams(lp);
img.setBackgroundResource(R.drawable.c1);
layout.addView(img);

}
@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;
}
}

希望这有帮助。

关于java - 如何用java在布局中放置图像?安卓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15238873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com