0
如何在點擊按鈕時動態添加圖像按鈕?我需要以2x3格式添加圖像按鈕,當它離開屏幕時,它應該可以水平滾動。[Android]如何在點擊按鈕時動態添加圖像按鈕?
package com.example.dynamic;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
LinearLayout linearLayout1;
LinearLayout linearLayout2;
int flag=0;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
linearLayout2 = (LinearLayout) findViewById(R.id.linearLayout2);
}
public void onClick(View v){
ImageView image = new ImageView(MainActivity.this);
image.setBackgroundResource(R.drawable.ic_launcher);
if(flag==0){
linearLayout1.addView(image);
flag=1;
}
else{
linearLayout2.addView(image);
flag=0;
}
}
}
,這是我使用的佈局:
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Button" />
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/linearLayout1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/linearLayout2"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
</LinearLayout>
這樣做的問題是,當圖像按鈕的數量超過屏幕寬度,這不是滾動。另一個潛在的問題是可能分別滾動2行而不是在一起。這是不可取的。請幫助我,我是一個初學者,並在問這個問題時饒恕我的任何錯誤。
非常感謝。那正是我想要的。但我仍然有一些疑問。如果我使用[this](http://www.dev-smart.com/archives/34)作爲水平滾動視圖,我將如何實現2行,並在點擊按鈕時動態添加列? – mkr231
您應該搜索水平網格視圖,或者您的列表視圖項目應該有兩個佈局。 – user2729200
我發現[this](https://github.com/jess-anders/two-way-gridview),我相信會做這項工作。 – mkr231