Android Presentation雙屏異顯,副屏的操作

最近有一個雙屏顯示的需求,當時一臉蒙逼完全不知如何着手,不負衆望找到解決辦法,在Android4.2版本以後提供了Presentation類,可以輕鬆實現在兩塊屏幕上同時顯示不同的內容。做一下筆記。

Presentation是一個特殊的dialog,它的目的是顯示內容到第二屏幕。在Presentation創建的時候關聯一個目標設備,確定Presentation要顯示在那個設備上,根據這個設備的信息來配置Presentation的context和resources信息。

上代碼

public class MainActivity extends AppCompatActivity {

private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = findViewById(R.id.webView);
    webView.loadUrl("https://www.baidu.com/");
    webView.getSettings().setJavaScriptEnabled(true);
	//這裏面是主要的代碼
    setCustomerProductList();
}
@SuppressLint("NewApi")
private void setCustomerProductList() {
    DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
    Display[] presentationDisplays = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION);
    if (presentationDisplays.length > 0) {
        // If there is more than one suitable presentation display, then we could consider
        // giving the user a choice.  For this example, we simply choose the first display
        // which is the one the system recommends as the preferred presentation display.
        Display display = presentationDisplays[0];
        Presentation presentation = new DifferentDislay(this, display);
        presentation.show();
    }
}
}

新建一個類繼承Presentation

public class DifferentDislay extends Presentation {

    public DifferentDislay(Context outerContext, Display display) {
        super(outerContext,display);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        
    }
}

在副屏操作,或者跳轉頁面

public class DifferentDislay extends Presentation {
private Context context;
private TextView img;
private Display display;

    public DifferentDislay(Context outerContext, Display display) {
        super(outerContext,display);
        this.context = outerContext;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        img = findViewById(R.id.img);

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Presentation presentation = new PresentationActivity(context, display);
                presentation.show();
            }
        });
    }
}

副屏跳轉頁面是跳轉到新建的一個Presentation

別忘了加權限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<!-- 在 屏幕最頂部顯示addview-->
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章