我的主要目标是单击 Activity1
中的按钮,然后 Activity2
的 WebView
从本地 html 文件加载页面。
仅出于测试目的,我将只使用 1 个按钮,但就个人而言,我将使用 1 个以上的按钮,每个按钮将导航到不同的页面。
这是我在 Activity1
中打开 Activity2
的代码
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
这就是我想要在 Activity2
加载后加载的内容
setContentView(R.layout.activity_main);
WebView view = new WebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/index.html");
view.setBackgroundColor(Color.TRANSPARENT);
setContentView(view);
我可以用 1 个按钮来完成吗?但是当我想在 Activity1
中使用不同的按钮时,问题就来了,不同的页面比如 index.html2 或 index.html3。谁能帮帮我?
谢谢。
最佳答案
你应该想想你的问题是什么。
您在 Activity1 中有一个按钮。 单击该按钮会启动 Activity2 并在那里执行一些特定的操作(例如打开 index1.html)。
现在您想向 Activity1 添加更多按钮。
每个按钮也应打开 Activity2。但是每个按钮都应该做一些特定的事情(比如打开“index1.html”、“index2.html”或“index3.html”中的一个)。
那么你的问题是什么? 你不知道如何告诉 Activity2 哪个 Button 被点击了,所以 Activity2 不知道打开哪个“index.html”。
现在,让我告诉你怎么做:
您已经在使用此代码启动 Activity2:
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
但是 Intent
可以做的远不止启动 Activity
!
您可以将数据添加到 intent-object,稍后取回它们。
通过执行此操作将数据添加到您的 Intent 中:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("htmlToOpen", "index1.html"); //Here you put your info
startActivity(intent);
现在,在您的 Activty2 中,您必须取回数据:
String fileName = getIntent().getStringExtra("htmlToOpen");
现在您可以使用字符串文件名打开您想要的 html 文件:
setContentView(R.layout.activity_main);
WebView view = new WebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/" + fileName);
view.setBackgroundColor(Color.TRANSPARENT);
setContentView(view);
要了解有关 Intent
的更多信息,请阅读此处:Intents and Intent Filters
顺便说一句:我认为您正在尝试执行以下操作:
- 您在
MainActivity
中启动您的应用。 - 你有一个按钮。用户可以点击按钮打开 Activity1。
- 在 Activity1 中,用户可以选择一个网站(html 文件)。
- 网站现在应该显示在
MainActivity
中。
如果这是你想做的,让我推荐 Android 的方式来做:
在您的 MainActivity
中,您通过执行以下操作启动 Activity1:
Intent i = new Intent(this, Activity1.class);
startActivityForResult(i, 1);
该代码意味着您启动 Activity1 只是为了返回结果(在本例中,结果是所需的网站)。
现在,在您的 Activity1 中,您通过执行以下操作返回结果(所需网站):
Intent returnIntent = new Intent();
returnIntent.putExtra("htmlToOpen","index1.html"); //if another button was clicked, put another filename, here.
setResult(RESULT_OK,returnIntent);
finish();
现在,再次回到您的 MainActivity
,您可以通过添加以下函数获得结果:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String fileName = data.getStringExtra("htmlToOpen");
//Now open your desired website by using the String fileName,
//which contains the String "index1.html"
}
}
}
如果您想了解有关为结果启动 Activity 的更多信息,请阅读:
关于android studio点击activity1中的button1加载activity2 webview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30777800/