从 Activity AlertDialog 添加到 Fragment ArrayAdapter

Posted

技术标签:

【中文标题】从 Activity AlertDialog 添加到 Fragment ArrayAdapter【英文标题】:Adding to Fragment ArrayAdapter from Activity AlertDialog 【发布时间】:2017-03-31 13:16:13 【问题描述】:

我正在学习在 android Studio 中制作原型,但遇到了一个我似乎找不到任何答案的问题。

我有一个将自定义 ArrayAdapter 显示为 ListView 的 Activity。我可以通过单击它们并在生成的 AlertDialog 中键入来编辑 ListView 中的项目。还有一个我可以按下的添加按钮,它会弹出一个类似的 AlertDialog,但是当我点击保存时,没有任何内容会添加到 ListView。如何获取 AlertDialog 文本输入以另存为新的 ArrayAdapter 项?

我发现的大多数示例都是直接在 Activity 中实例化 ArrayAdapter,而不是像我那样通过 Fragment 实例化。

MainActivity.java

public class MainActivity extends AppCompatActivity 

private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState)  //initialize the activity
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); //establish where the layout will come from
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //creates a toolbar
    setSupportActionBar(toolbar);

    if (findViewById(R.id.fragment_container) != null) 
        if (savedInstanceState != null) 
            return;
        
        //creates the first fragment dynamically, so it can be replaced
        Fragment firstFragment = new MainActivityFragment();
        firstFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    

    //This creates the Floating Action Button
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            createDialog();
        

        private void createDialog() 
            ArrayList<User> users = new ArrayList<User>();

            // create an AlertDialog that'll come up when the add button is clicked
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

            // set title
            alertDialog.setTitle("Add item");

            final EditText input = new EditText(MainActivity.this); //uses the EditText from dialog_set
            input.setInputType(InputType.TYPE_CLASS_TEXT); //makes the dialog ask for plain text input
            alertDialog.setView(input);

            // set up buttons

            alertDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() 

                @Override
                public void onClick(DialogInterface dialog, int which) 
                    String textInput = input.getText().toString(); //saves user text as a string
                    Log.d(TAG, textInput); // records input as a log
                    CustomUsersAdapter.this.add(textInput);
                
            );

            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface dialog, int which) 
                    dialog.cancel();
                
            );

            // show it
            alertDialog.show();
        
    );

MainActivityFragment.java

public class MainActivityFragment extends Fragment 

@BindView(R.id.lvUsers) ListView listView;

public MainActivityFragment() 


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    ButterKnife.bind(this, view);

    ArrayList<User> arrayOfUsers = new ArrayList<User>();
    arrayOfUsers.add(new User("Person 1", "Hometown 1"));
    arrayOfUsers.add(new User("Person 2", "Hometown 2"));
    arrayOfUsers.add(new User("Person 3", "Hometown 3"));
    arrayOfUsers.add(new User("Person 4", "Hometown 4"));
    arrayOfUsers.add(new User("Person 5", "Hometown 5"));
    // Create the adapter to convert the array to views
    CustomUsersAdapter adapter = new CustomUsersAdapter(getContext(), arrayOfUsers);
    // Attach the adapter to a ListView
    listView.setAdapter(adapter);

    return view;

CustomUsersAdapter.java

public class CustomUsersAdapter extends ArrayAdapter<User> 
private ArrayList<User> users;

public CustomUsersAdapter(Context context, ArrayList<User> users) 
    super(context, 0, users);
    this.users = users;


@Override
public View getView(final int position, View convertView, ViewGroup parent) 
    // Get the data item for this position
    User user = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) 
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_user, parent, false);
    
    // Lookup view for data population
    TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
    TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
    // Populate the data into the template view using the data object
    tvName.setText(user.name);
    tvHome.setText(user.hometown);

    convertView.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            createDialog(position);
        
    );

    // Return the completed view to render on screen
    return convertView;


protected void add(String textInput) 
    add(new User(textInput, "Incomplete"));


private void createDialog(final int position) 
    // create an AlertDialog that'll come up when text is clicked
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            getContext());

    // set title
    alertDialog.setTitle("Edit item");

    final EditText input = new EditText(getContext()); //uses the EditText from dialog_set
    input.setInputType(InputType.TYPE_CLASS_TEXT); //makes the dialog ask for plain text input
    alertDialog.setView(input);

    // set up buttons

    alertDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() 

        @Override
        public void onClick(DialogInterface dialog, int which) 
            String textInput = input.getText().toString(); //saves user text as a string
            users.get(position).name = textInput;
            notifyDataSetChanged();
        
    );

    alertDialog.setNeutralButton("Complete", new DialogInterface.OnClickListener() 
        @Override
        public void onClick(DialogInterface dialog, int which) 
            users.get(position).hometown = "Complete";
            notifyDataSetChanged();
        
    );

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
        @Override
        public void onClick(DialogInterface dialog, int which) 
            dialog.cancel();
        
    );

    // show it
    alertDialog.show();

ListView 布局(来自 fragment_main.xml)

<ListView
    android:id="@+id/lvUsers"
    android:layout_
    android:layout_
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" >

</ListView>

【问题讨论】:

I can edit the items in the ArrayAdapter by clicking on them。不可能的。数组适配器没有 gui 元素,没有视图,因此无法点击。请改写。 你有 FAB 在 Activity 和 Fragment 中的原因吗? @greenapps,我稍微改变了措辞 - 现在更清楚了吗? @BlackHatSamurai,不是吗?它已经在活动中(我使用了已经包含 FAB 的模板),就像我说的,我正在学习,所以我一直在使用我可用的东西。将 FAB 移动到片段是否有用? that displays a custom ArrayAdapter as an ArrayList. I can edit the items in the ArrayList by clicking on them。也是不可能的。数组列表是不可见的。它不是gui元素。这是没有意见。所以你不能点击它。请重试。 【参考方案1】:

您有几个问题。首先,您尝试使用静态调用更新您的适配器,但您不能这样做。您还需要调整您的add 方法。它应该类似于:

protected void add(String textInput) 
    this.users.add(new User(textInput, "Incomplete"));

这只是问题的一部分。您需要将对象引用传递给onClickListener。您正在尝试进行静态调用。这行不通。我可能会考虑放置浮动操作按钮。如果你这样做了,那么你可以轻松地将引用传递给适配器:

public class MainActivityFragment extends Fragment 

private final CustomUsersAdapter adapter;
@BindView(R.id.lvUsers) ListView listView;


public MainActivityFragment() 


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    ButterKnife.bind(this, view);

    ArrayList<User> arrayOfUsers = new ArrayList<User>();
    arrayOfUsers.add(new User("Person 1", "Hometown 1"));
    arrayOfUsers.add(new User("Person 2", "Hometown 2"));
    arrayOfUsers.add(new User("Person 3", "Hometown 3"));
    arrayOfUsers.add(new User("Person 4", "Hometown 4"));
    arrayOfUsers.add(new User("Person 5", "Hometown 5"));
    // Create the adapter to convert the array to views
   adapter = new CustomUsersAdapter(getContext(), arrayOfUsers);
    // Attach the adapter to a ListView
    listView.setAdapter(adapter);

    return view;


//This creates the Floating Action Button
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            createDialog();
        

        private void createDialog() 
            ArrayList<User> users = new ArrayList<User>();

            // create an AlertDialog that'll come up when the add button is clicked
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

            // set title
            alertDialog.setTitle("Add item");

            final EditText input = new EditText(MainActivity.this); //uses the EditText from dialog_set
            input.setInputType(InputType.TYPE_CLASS_TEXT); //makes the dialog ask for plain text input
            alertDialog.setView(input);

            // set up buttons

            alertDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() 

                @Override
                public void onClick(DialogInterface dialog, int which) 
                    String textInput = input.getText().toString(); //saves user text as a string
                    Log.d(TAG, textInput); // records input as a log
                   adapter.add(textInput);
                
            );

            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                @Override
                public void onClick(DialogInterface dialog, int which) 
                    dialog.cancel();
                
            );

            // show it
            alertDialog.show();
        
    );

通过执行这样的操作,您可以将对适配器的引用传递到您创建的内部类中,然后对其进行更新。希望这可以帮助。

【讨论】:

以上是关于从 Activity AlertDialog 添加到 Fragment ArrayAdapter的主要内容,如果未能解决你的问题,请参考以下文章

Android中activity定义的AlertDialog调用不弹出!

AlertDialog 用法大全

AlertDialog.java

AlertDialog,Toast对Activity生命周期的影响

Android探究2:Android 5.0下 Dialog&AlertDialog 并不会影响Activity的生命周期

从 AlertDialog 输入将项目添加到 RecyclerView