我的项目中有一个LinearLayout和一些按钮。我想在点击每个Button时从drawable向LinearLayout添加一个小图像。如何以编程方式将图像添加到LinearLayout?
这是我在HorizontalScrollView中的LinearLayout:
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
>
<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
这是我的活动:
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout notes = (LinearLayout) findViewById(R.id.LinearLayout_notes);
final ImageView notes_do = new ImageView(this);
notes_do.setBackgroundResource(R.drawable.notes_do);
new Thread(new Runnable() {
@Override
public void run() {
final ImageButton img_1 = (ImageButton) findViewById(R.id.img_1_);
img_1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if( event.getAction() == MotionEvent.ACTION_DOWN ) {
notes.addView(notes_do);
}
return true;
}
}); // end of ontouch
}
}).start(); // end of thread
} // end of oncreate
}// end of activity
谢谢。
答案 0 :(得分:12)
LinearLayout ll = (LinearLayout)findViewById(R.id.LinearLayout1);
for(int i=0;i<5;i++)
{
ImageView ii= new ImageView(this);
ii.setBackgroundResource(R.drawable.ic_action_search);
ll.addView(ii);
}
答案 1 :(得分:2)
您可以对linearlayout执行findViewById,并在按钮的onclicklistener中动态添加一个imageview
LinearLayout linLay = (LinearLayout)findViewById(R.id.LinearLayout1);
ImageView image = new ImageView(this);
//add image to imageview
...
linLay.addView(image);
答案 2 :(得分:1)
ImageView img = new ImageView( this);
LinearLayout rl = (LinearLayout) findViewById(R.id.LinearLayout1);
LinearLayout.LayoutParams viewParamsCenter = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
img.setImageResource(R.drawable.ic_launcher);
img.setLayoutParams(viewParamsCenter);
rl.add(img);
答案 3 :(得分:1)
如果要动态设置图像,请单击按钮。您可以将图像视图添加到线性布局
View LinearLayout1 = findViewById(R.id.Layout1);
ImageView image1 = new ImageView(getApplicationContext());
String uri = "@drawable/myresource.png"; // Here you can set the name of
// the image dynamically
int imageResource = getResources().getIdentifier(uri, null,
getPackageName());
Drawable res = getResources().getDrawable(imageResource);
image1.setImageDrawable(res);
((ViewGroup) LinearLayout1).addView(image1);