如何以编程方式创建“链接”按钮?

时间:2018-01-04 17:38:15

标签: android user-interface button

我正在尝试转换一系列按钮,这些按钮将在浏览器中将网页从xml布局文件打开到我的Activity类(以编程方式)。我怎样才能做到这一点?

我一直无法找到回答此问题的问题。

3 个答案:

答案 0 :(得分:1)

  /**
     * Open the specified URL on the device's browser
     *
     * @param context Current Context.
     * @param url     The url to display.
     */
    public static void openWebPage(@NonNull Context context, String url) {
        Uri webPage = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, webPage);
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        }
    }

然后在您的活动的onCreate中,您会看到按钮:

View button = findViewById(R.id.my_button);
button.setOnClickListener(new onClickListener(){
   ... // call the above method with the corresponding url
});

更多信息here

答案 1 :(得分:0)

代码......

public class MainActivity extends Activity {

 TextView textView;
 Spanned spannedText;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 textView = (TextView)findViewById(R.id.textView1);

 spannedText = Html.fromHtml("text with a link in it <br />" +
 "<a href='https://www.aol.com//'>aol.com</a>");

 textView.setMovementMethod(LinkMovementMethod.getInstance());
 textView.setText(spannedText);
 }
}

XML TextView

 <TextView
 android:id="@+id/textView1"
 android:layout_width="match_content"
 android:layout_height="match_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="LINK WILL SHOW UP HERE"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:gravity="center" />

答案 2 :(得分:-1)

您需要在Android应用程序中使用webview。 More about web view