【问题标题】:How can I link a Listview to an AlertDialog如何将 Listview 链接到 AlertDialog
【发布时间】:2017-07-12 11:24:01
【问题描述】:

我创建了一个单独的 ListView 类,它将显示公司的名称。现在我想将此列表视图传递给 Main Activity 上的 AlertDialog。我创建了一个列表布局和一个文本布局来显示列表的项目。现在我为 Alertdialog 创建了另一个布局。我想在第一页上按下按钮时显示此对话框。如何在此 Alerdialog 中传递 listView。这是我的主要活动代码

public class MainActivity extends AppCompatActivity {

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

    Button button=(Button) findViewById(R.id.button);

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

public void showDialog(){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.diallog_layout, null);
    builder.setView(dialogView);
    builder.setCancelable(true);
    builder.setTitle("Contact");

    ListViewActivity listViewActivity=new ListViewActivity();

    //how can I show li list item here?
  }
}

我的 ListViewActivityClass 是

public class ListViewActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_layout);
    populateListView();

}
private void populateListView() {
    //Create list of items
    String[] company= getResources().getStringArray(R.array.company_name);
    //Build Adapter
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(
            this, //Context for the Activity
            R.layout.first_alertlist_textstyle,
            android.R.id.text1,//Layout to use
            company); //Items to be displayed

    //Configure the list view
    ListView companyList =(ListView) findViewById(R.id.list_view);
    TextView alertTitle = (TextView) findViewById(R.id.title);
    companyList.setAdapter(adapter);

  }
}

我的列表布局是

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    />
</LinearLayout>

显示列表项的文本布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:gravity="center"
    />
</LinearLayout>

对话框布局是

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Contact"
    android:gravity="center_horizontal"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:layout_gravity="center"
    />

  </LinearLayout>

编辑代码

public class MainActivity extends AppCompatActivity {

ArrayList<Bean> bean=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.option_menu_laout);

    Button button=(Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Alert();
            Toast.makeText(MainActivity.this, "Dialog", Toast.LENGTH_SHORT).show();
        }
    });
}

private void Alert(){
    ArrayList<Bean> bean=new ArrayList<>();
    View view = getLayoutInflater().inflate(R.layout.rating_dialog_layout, null);
    ListView details = (ListView) view.findViewById(R.id.ratingListViewId);
    Adapter adapter = new Adapter(bean,getApplicationContext());
    details.setAdapter(adapter);

    final AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Select");
    builder.setView(view);

    builder.setCancelable(false);
    builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });
    details.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {

            ;
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

}

【问题讨论】:

    标签: android listview dialog android-alertdialog


    【解决方案1】:

    只需创建一个自定义对话框,如下所示:

    http://www.edumobile.org/android/custom-listview-in-a-dialog-in-android/

    或者看下面的例子:

    private void showDialog(){
    
        final Dialog dialog = new Dialog(this);
    
        View view = getLayoutInflater().inflate(R.layout.dialog_main, null);
    
        ListView lv = (ListView) view.findViewById(R.id.custom_list);
    
        // Change MyActivity.this and myListOfItems to your own values
        CustomListAdapterDialog clad = new CustomListAdapterDialog(MyActivity.this, myListOfItems);
    
        lv.setAdapter(clad);
    
        lv.setOnItemClickListener(........);
    
        dialog.setContentView(view);
    
        dialog.show();
    
    }
    

    【讨论】:

    • myListOfItems 是什么意思。
    • 表示任何数据列表
    • 好的,但我已经在我的 ListviewClass 中使用了列表。有什么方法可以显示带有此数据的对话框选项?
    • 是的,因为在链接中您需要一个自定义适配器
    • 你能解释一下我该怎么做吗?我是android开发的新手
    【解决方案2】:
    call this on Button Click
     private void Alert(){
            View view = getLayoutInflater().inflate(R.layout.rating_dialog_layout, null);
            ListView details = (ListView) view.findViewById(R.id.ratingListViewId);
            Adapter adapter = new Adapter(bean,getApplicationContext());
            details.setAdapter(adapter);
    
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Select");
            builder.setView(view);
    
            builder.setCancelable(false);
            builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            detailsbtn.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
    
                    alertdialog.dismiss();
                }
            });
            alertdialog = builder.create();
            alertdialog.show();
        }
    
    use Bean Class
    
    public class Bean {
        public Bean(String _id, String description) {
            this._id = _id;
            this.description = description;
        }
    
        String _id;
        String description;
    
        public String get_id() {
            return _id;
        }
    
        public void set_id(String _id) {
            this._id = _id;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    }
    
    use Adapter
    
    public class Adapter extends BaseAdapter {
    
        Context context;
        List<Bean> list=new ArrayList<Bean>();
    
        public Adapter(ArrayList<Bean> list, Context context) {
            this.context = context;
            this.list = list;
        }
    
        @Override
        public int getCount() {
            return list.size();
        }
    
        @Override
        public Object getItem(int position) {
            return list.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
    
            LayoutInflater inflater=LayoutInflater.from(context);
            View v=inflater.inflate(R.layout.rating_layout_row,null);
    
            TextView idTv= (TextView) v.findViewById(R.id.id);
            TextView nameTv= (TextView) v.findViewById(R.id.name);
    
            idTv.setText(String.valueOf(list.get(position)._id()));
            nameTv.setText(list.get(position).getDescription());
            return v;
        }
    }
    

    创建 rating_layout_row

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/activity_vertical_margin">
    
        <TextView
            android:id="@+id/id"
            android:textColor="#000000"
            android:layout_width="match_parent"
            android:visibility="gone"
            android:layout_height="wrap_content"/>
    
        <TextView
            android:id="@+id/name"
            android:textColor="#000000"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
    
    
    </LinearLayout>
    

    创建自定义布局 rating_dialog_layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
    
        android:layout_height="match_parent">
    
        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/ratingListViewId"
            android:layout_gravity="center_horizontal" />
    </LinearLayout>
    

    【讨论】:

    • 这段代码不完整。你从哪里得到这个 bean 按钮
    • 也在你的适配器类中发现了这一行的问题 idTv.setText(String.valueOf(list.get(position)._id()));
    • 我在哪里使用 bean Button?
    • 适配器适配器 = new Adapter(bean,getApplicationContext());alertdialog = builder.create(); alertdialog.show();此行显示错误
    • 我修好的那个。但是你在应用程序上下文和详细信息btn、alertdialog 之前从哪里得到bean
    【解决方案3】:

    如果您的目的是在对话框中显示列表,请阅读警告对话框文档:Alert dialog

    Alert 对话框的 Builder 类有很多方法来实现列表:

    builder.setItems for list string
    builder.setMultiChoiceItems
    builder.setSingleChoiceItems
    

    【讨论】:

      【解决方案4】:

      您可以使用以下代码创建一个简单的列表警报对话框...

      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
      alertDialogBuilder.setTitle("Awesome alert")
      .setCancelable(false)
      .setAdapter(new NotificationListAdapter(mContext, listItems), new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
      
                  // on item click...
      
                  dialog.cancel();
              }
          })
      .setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
      
                  dialog.cancel();
      
              }
          });
      AlertDialog alertDialog = alertDialogBuilder.create();
      alertDialog.show();
      

      试试这样的 BaseAdapter。

      public class NotificationListAdapter extends BaseAdapter {
      
      private Context mContext;
      private List<NotificationModel> notificationModels;
      
      public NotificationListAdapter(Context mContext, List<NotificationModel> notificationModels) {
          this.mContext = mContext;
          this.notificationModels = notificationModels;
      }
      
      @Override
      public int getCount() {
          return notificationModels.size();
      }
      
      @Override
      public NotificationModel getItem(int i) {
          return notificationModels.get(i);
      }
      
      @Override
      public long getItemId(int i) {
          return i;
      }
      
      @Override
      public View getView(int position, View view, ViewGroup viewGroup) {
      
          NotificationViewHolder notificationViewHolder;
      
          if (view == null) {
      
              LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
              view = mInflater.inflate(R.layout.item_notification, null);
      
              notificationViewHolder = new NotificationViewHolder();
      
              notificationViewHolder.item_view = (RelativeLayout) view.findViewById(R.id.notification_item);
              notificationViewHolder.textView_notification = (TextView) view.findViewById(R.id.tv_notification);
              notificationViewHolder.textView_time = (TextView) view.findViewById(R.id.tv_notification_time);
      
              view.setTag(notificationViewHolder);
      
          } else {
              notificationViewHolder = (NotificationViewHolder) view.getTag();
          }
      
          NotificationModel notificationModel = getItem(position);
      
          // UI Update...(Data binding)
      
          return view;
      }
      
      private class NotificationViewHolder {
          RelativeLayout item_view;
          TextView textView_notification, textView_time;
      }
      }
      

      如果您需要有关此的更多信息。请在下方发表评论...祝您编码愉快...

      【讨论】:

      • 如何在这里传递我的 ListView 数据
      • 去思考我的代码。 new NotificationListAdapter(mContext, listItems)。请将您的物品发送到适配器类。
      • @Divankar 我真的很喜欢你编码的方式。但是您的代码有点不完整。我是 android 开发的新手。如果你不介意,你能用例子详细说明你的代码吗
      • @ktina 我在 Github 中为你添加了示例。请尝试我的示例 - link
      • 非常感谢您提供的链接。我会试试这个代码,让你知道
      【解决方案5】:

      在你的主要活动中写:

      public class MainActivity extends AppCompatActivity {
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.option_menu_laout);
      
          Button button=(Button) findViewById(R.id.button);
      
          button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  openCompaniesActivity()
              }
          });
      }
      
      public void openCompaniesActivity()(){   
          startActivity(new Intent(this, ListViewActivity.class));
        }
      }
      

      您的 ListViewActivity:

      public class ListViewActivity extends Activity{
      
      String[] company;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.list_layout);
          populateListView();
      
      }
      private void populateListView() {
          //Create list of items
          company= getResources().getStringArray(R.array.company_name);
          //Build Adapter
          ArrayAdapter<String> adapter=new ArrayAdapter<String>(
                  this, //Context for the Activity
                  R.layout.first_alertlist_textstyle,
                  android.R.id.text1,//Layout to use
                  company); //Items to be displayed
      
          //Configure the list view
          ListView companyList =(ListView) findViewById(R.id.list_view);
          companyList.setAdapter(adapter);
          companyList.setOnItemsClickListener(new AdapterView.OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                      String selectedCompany = company[position];
                      //Create you dialog, depending from selected company.
                      AlertDialog.Builder builder = new AlertDialog.Builder(ListViewActivity.this);
                      LayoutInflater inflater = ListViewActivity.this.getLayoutInflater();
                      View dialogView = inflater.inflate(R.layout.diallog_layout, null);
                      builder.setView(dialogView);
                      builder.setCancelable(true);
                      builder.setTitle("Contact");
                      builde.show(); 
                  }
              })
      
        }
      }
      

      不要忘记将所有需要的活动添加到清单中。

      【讨论】:

      • companyList.setOnClickListener(new AdapterView.OnItemClickListener() 有一个问题。它在适配器视图中显示无法应用
      • 问题:错误:(40, 20) 错误:没有为 setOnClickListener() 方法找到合适的方法 View.setOnClickListener(OnClickListener) 不适用(参数不匹配; 不能转换为 OnClickListener) 方法 AdapterView.setOnClickListener(OnClickListener) 不适用(参数不匹配; 无法转换为 OnClickListener)
      • 您可能会尝试使用 View.OnClickListener(...) 而不是 AdapterView.OnItemClickListener(...);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 2015-06-05
      • 2012-09-15
      相关资源
      最近更新 更多