android - 如何以编程方式将图像添加到 LinearLayout?

标签 android imageview android-linearlayout

我的项目中有一个 LinearLayout 和一些 Buttons。我想在单击每个 Button 时从 drawable 向 LinearLayout 添加一个小图像。如何以编程方式将图像添加到 LinearLayout?

这是我在 Horizo​​ntalScrollView 中的 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>

这是我的 Activity :

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

最佳答案

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

关于android - 如何以编程方式将图像添加到 LinearLayout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14582620/

相关文章:

用于密码验证的php

android - 如何在没有用户确认的情况下使用强制 adb 进行备份?

android - 按钮的真正自定义形状

android - android XML 中图像缺少 contentDescription 属性

java - android:如何找到表单小部件或 ImageView 的位置?

android - 布局边距不适用于 android 2.3.3

java - 跟踪位置以动画 fragment 之间的过渡

android - ImageView 上的 drawCircle 坐标错误

imageview - 使用 fxml/javafx 加载 .tif/.tiff

android - LinearLayout 中的 ImageView