Android TvView:更改宽高比

Hei*_*erg 5 android aspect-ratio

我在我的 android 电视应用程序中使用它android.media.tv.TvView来在应用程序内的小空间(片段)中观看直播电视。

在观看现场板球比赛时,客户抱怨他们看不到底部的比分。如何调整宽高比或缩放内容TvView来解决此问题?

我的片段布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.media.tv.TvView
        android:id="@+id/tvView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

初始化TvView的片段代码:

TvInputManager mTvInputManager = (TvInputManager) requireContext()
                .getSystemService(Context.TV_INPUT_SERVICE);
List<TvInputInfo> inputs = mTvInputManager.getTvInputList();

List<String> ids = new ArrayList<>();
for (TvInputInfo info : inputs) {
     if (info.getType() == type) {
         String id = info.getParentId() != null ? info.getParentId() : info.getId();
         if (!ids.contains(id)) {
             ids.add(id);
         }
     }
}
int idx = viewModel.deviceDetails.getSettings().getOtherDetails().getPort() - 1;
String id = ids.get(idx);
tvView.setVisibility(View.VISIBLE);
tvView.tune(id, TvContract.buildChannelUriForPassthroughInput(id));
Run Code Online (Sandbox Code Playgroud)

Hei*_*erg 0

android.media.tv.TvView 类不提供直接方法来设置宽高比。但是,您可以通过调整 TvView 在其父布局中的布局参数来实现所需的宽高比。

以下示例说明了如何以编程方式设置 TvView 的宽高比:

TvView tvView = findViewById(R.id.tv_view); // Assuming you have a TvView in your layout

// Calculate the desired aspect ratio (e.g., 16:9)
float aspectRatio = 16f / 9f;

// Get the parent layout of the TvView
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) tvView.getLayoutParams();

// Calculate the new width and height based on the aspect ratio
int width = getResources().getDisplayMetrics().widthPixels;
int height = (int) (width / aspectRatio);

// Set the new width and height
layoutParams.width = width;
layoutParams.height = height;

// Apply the new layout parameters to the TvView
tvView.setLayoutParams(layoutParams);
Run Code Online (Sandbox Code Playgroud)

在此示例中,我们根据所需的宽高比(本例中为 16:9)计算 TvView 的新宽度和高度。我们假设 TvView 的宽度应与设备屏幕的宽度匹配。然后,我们通过宽度除以纵横比来计算高度。最后,我们更新 TvView 的布局参数以反映新的宽度和高度。

通过动态调整TvView的布局参数,您可以在Android上实现TvView所需的宽高比。