草庐IT

android - 创建带有选项列表的弹出窗口,例如 Youtube App

coder 2023-12-26 原文

我正在尝试创建一个类似于 Youtube 应用的 View ,如下所示:

点击我将打开一个对话框,如下所示:

是否有任何已经由 android 构建的 View 或库可以帮助我创建它,还是我需要自己创建它?

我试着搜索它,但找不到任何东西。

最佳答案

尝试这种我已经成功使用的方式

Dialogs

  • 对话框是提示用户做出决定或输入附加信息的小窗口。对话框不会填满屏幕,通常用于要求用户先执行操作才能继续的模态事件。

RecyclerView

  • 一种灵活的 View ,可以在有限的窗口内查看大型数据集。

示例代码

MainActivity

public class MainActivity extends AppCompatActivity {


    RelativeLayout myRelativeLayout;
    TextView tvText;

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

        myRelativeLayout = findViewById(R.id.myRelativeLayout);
        tvText = findViewById(R.id.tvText);

        myRelativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCustomDialog();
            }
        });
    }

    private void showCustomDialog() {

        final Dialog myDialog = new Dialog(this);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        RecyclerView myRecyclerView;
        DataAdapter dataAdapter;
        ArrayList<DataModel> arrayList = new ArrayList<>();

        Button btnCancel;

        // setting custom layout in out dialog
        myDialog.setContentView(R.layout.custom_dialog_layout);

        // findViewById for views inside dialog
        myRecyclerView = myDialog.findViewById(R.id.MyRecyclerView);
        btnCancel = myDialog.findViewById(R.id.btnCancel);

        // programatically setting hight and witdh of dialog
        Window window = myDialog.getWindow();
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

        // setting gravity of dialog so it will diaply in the center of screen
        window.setGravity(Gravity.CENTER);

        // setting TRANSPARENT Background to myDialog to display myDialog with rounded corner
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        // adding data in to arrayList

        arrayList.add(new DataModel("Very Small", false));
        arrayList.add(new DataModel("Small", false));
        arrayList.add(new DataModel("Normal", true));
        arrayList.add(new DataModel("Large", true));
        arrayList.add(new DataModel("Very Large", true));

        // using DataAdapter.OnItemClickListener() getting result which item is selected in recyclerview
        dataAdapter = new DataAdapter(this, arrayList, new DataAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DataModel item, int position) {
                // setting result in a textview when user select recyclerview item
                tvText.setText(item.getName());
            }
        });

        // setting LayoutManager in myRecyclerView
        myRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        // setting Adapter( in myRecyclerView
        myRecyclerView.setAdapter(dataAdapter);

        // click listner for btnCancel to dismiss myDialog
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
            }
        });

        // used for display Dialog
        myDialog.show();
    }


}

layout.activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">


    <RelativeLayout
        android:id="@+id/myRelativeLayout"
        android:layout_width="match_parent"
        android:padding="5dp"
        android:layout_height="wrap_content"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_centerInParent="true"
            android:padding="5dp"
            android:text="Language"
            android:textColor="@android:color/black" />

        <TextView
            android:id="@+id/tvText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerInParent="true"
            android:drawableEnd="@drawable/ic_arrow"
            android:gravity="center"
            tools:text="Deafult" />
    </RelativeLayout>
</LinearLayout>

layout.custom_dialog_layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="20dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="Text Size"
            android:textColor="@android:color/black"
            android:textSize="20sp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:layout_marginTop="5dp"
            android:background="@android:color/darker_gray" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/MyRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="270dp" />


        <Button
            android:id="@+id/btnCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:background="@drawable/round_button"
            android:paddingStart="50dp"
            android:paddingEnd="50dp"
            android:text="Cancel"
            android:textColor="#00b7ff" />
    </LinearLayout>

</android.support.v7.widget.CardView>

DataAdapter

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    private Context context;
    private ArrayList<DataModel> arrayList = new ArrayList<>();
    private final OnItemClickListener listener;


    public DataAdapter(Context context, ArrayList<DataModel> arrayList, OnItemClickListener listener) {
        this.context = context;
        this.arrayList = arrayList;
        this.listener = listener;
    }


    private int lastCheckedPosition = -1;

    @NonNull
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.custom_row_item, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DataAdapter.ViewHolder viewHolder, int position) {

        // here i'm changing the state of radio button based on user select
        viewHolder.radioImage.setChecked(position == lastCheckedPosition);

        viewHolder.tvTextName.setText(arrayList.get(position).getName());

        // this is condition is used to hide line from thr last recyclerview item
        if (position == arrayList.size()-1) {
            viewHolder.bottomLine.setVisibility(View.GONE);
        } else {
            viewHolder.bottomLine.setVisibility(View.VISIBLE);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(DataModel item, int position);
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        View bottomLine;
        RadioButton radioImage;
        TextView tvTextName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);


            bottomLine = itemView.findViewById(R.id.bottomLine);
            radioImage = itemView.findViewById(R.id.radioImage);
            tvTextName = itemView.findViewById(R.id.tvTextName);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    arrayList.get(getAdapterPosition()).setSelected(true);
                    lastCheckedPosition = getAdapterPosition();

                    // getting result when user selecte radio button in your activity
                    listener.onItemClick(arrayList.get(lastCheckedPosition), lastCheckedPosition);

                    notifyDataSetChanged();

                }
            });
        }
    }
}

layout.custom_row_item

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    android:layout_marginStart="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="10dp">

    <TextView
        android:id="@+id/tvTextName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerInParent="true"
        android:padding="5dp"
        android:textColor="@android:color/black"
        tools:text="TextName" />


    <RadioButton
        android:id="@+id/radioImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerInParent="true"
        android:src="@drawable/ic__unchecked_radio_button" />

    <View
        android:id="@+id/bottomLine"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/tvTextName"
        android:layout_marginTop="10dp"
        android:background="@android:color/darker_gray" />

</RelativeLayout>

ic__unchecked_radio_button.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8z"/>
</vector>

ic_checked_radio_button.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,7c-2.76,0 -5,2.24 -5,5s2.24,5 5,5 5,-2.24 5,-5 -2.24,-5 -5,-5zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.42,0 -8,-3.58 -8,-8s3.58,-8 8,-8 8,3.58 8,8 -3.58,8 -8,8z"/>
</vector>

round_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">
    <!-- this one is ths color of the Rounded Button -->
    <solid android:color="#476e6e6e" />
    <!-- this one is used to set radius of the Rounded Button -->
    <corners android:radius="50dp" />
</shape>

OUTPUT

请查看此视频(以上代码的输出)https://www.youtube.com/watch?v=hGf-30Oh8OM

Screen-Shots

NOTE

您还可以使用 PopupWindow实现这一点

  • 此类表示可用于显示任意 View 的弹出窗口。弹出窗口是一个 float 容器,显示在当前 Activity 的顶部。

这里有一些不错的文章

关于android - 创建带有选项列表的弹出窗口,例如 Youtube App,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53133151/

有关android - 创建带有选项列表的弹出窗口,例如 Youtube App的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  5. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  8. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  9. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐