【发布时间】:2017-11-04 18:05:01
【问题描述】:
我已经找到了一些关于用 Java 而不是 XML 代码编写的动态按钮的内容。它工作正常,但我不知道如何使用这些 ID 以供进一步使用(单击它们时进行其他活动)。 当我在 XML 中编写按钮时,我知道如何使用方法 onClick,但在这里我迷路了。
我从https://alexanderoorayil.blogspot.si/2012/05/dynamic-button-in-android.html得到这个代码
我目前所拥有的:
public class MainActivity extends Activity {
Button b;
TextView t;
ScrollView scrollview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scrollview = new ScrollView(this);
LinearLayout linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollview.addView(linearlayout);
int num=15;
if(num!=0){
for(int i = 0; i<num;i++) {
LinearLayout linear1 = new LinearLayout(this);
linear1.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linear1);
b = new Button(this);
b.setText("Button" + i);
b.setId(i);
b.setTextSize(10);
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
linear1.addView(b);
}
}
else {
LinearLayout linear1 = new LinearLayout(this);
linear1.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linear1);
t = new TextView(this);
t.setText("No Buttons");
t.setTextSize(10);
linear1.addView(t);
}
this.setContentView(scrollview);
}
}
和 XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/horizontalScrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/buttonList">
</LinearLayout>
</HorizontalScrollView>
感谢您的帮助!
【问题讨论】:
-
试试这个链接,希望你能从中得到灵感stackoverflow.com/questions/44334532/…
-
感谢您的帮助,现在可以使用了!
标签: java android xml button dynamic