Id
这永远不会起作用,因为您的textViews 没有
尝试将此属性添加android:id="@+id/yourId"
到您的每个 textViews yourId 将取值从button1
tobutton5
onclick
在所有 textView 中只使用一种方法:
然后像这样称呼他们每个人
void onclick(View v)
{
switch(v.getId())
{
case R.id.button1:
//Code will be executed when you click on Button1
break;
case R.id.button2:
//Code will be executed when you click on Button2
break;
case R.id.button3:
//Code will be executed when you click on Button3
break;
.
.
.
.
default:
break;
}
}
更新
以下代码对我来说很好:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="234dp" >
<LinearLayout
android:layout_width="321dp"
android:id="@+id/myLinearLayout"
android:layout_height="154dp"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="224dp" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
Button [] myButton = new Button[100];
WebView wv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0;i<100;i++)
{
myButton[i] = new Button(this);
myButton[i].setOnClickListener(this);
myButton[i].setText("Button"+i);
LinearLayout ll = (LinearLayout)findViewById(R.id.myLinearLayout);
LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton[i], i);
}
}
@Override
public void onClick(View v)
{
for(int i=0;i<myButton.length;i++)
{
if(myButton[i]==v)
{
String s=Integer.toString(i);
wv=(WebView)findViewById(R.id.webView);
wv.loadUrl("file:///android_asset/chapter1.html"+s);
}
}
}
}
确保将以下行添加到您的 AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
演示