我有一个带按钮的布局。单击按钮后,我应该能够获得“操作栏共享按钮”(我们可以使用ShareActionProvider实现)的相同功能。试图在网上寻找一个例子;但找不到一个。这可能吗?
答案 0 :(得分:8)
是的,您可以通过触发隐式意图来响应Button按钮来实现相同的功能。如下例所示:
<强> Main.java 强>
public class MAIN extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SHARE(View view) {
// Do something in response to button
EditText content = (EditText) findViewById(R.id.editText1);
String shareBody = content.getText().toString();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "\n\n");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.a5)));
}
}
<强> layout_main.java 强>
<RelativeLayout 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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="31dp"
android:text="@string/MS1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:onClick="SHARE"
android:text="SEND" />
</RelativeLayout>
希望这有帮助。