How to dynamically add items to GridView Android Studio (Java)

放肆的年华 提交于 2021-01-29 06:48:40

问题


Hello I want to have an Add function that allows me to input items to my GridView

For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.

My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently

Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters

    //constructor - it takes the context and the list of words
    WordAdapter(Context context, ArrayList<WordFolder> word){
        super(context, 0, word);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View listItemView = convertView;
        if(listItemView == null){
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
        }

        //Getting the current word
        WordFolder currentWord = getItem(position);
        //making the 2 text view to match our word_folder.xml
        TextView title = (TextView) listItemView.findViewById(R.id.title);

        title.setText(currentWord.getTitle());

        TextView desc = (TextView) listItemView.findViewById(R.id.desc);

        desc.setText(currentWord.getTitleDesc());

        return listItemView;
    }
}

Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do

public class NewFolder extends AppCompatActivity {

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

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

        

        //If the user clicks the add button - it will save the contents to the Word Class
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //make TextView variables and cast the contents to a string and save it to a String variable
                TextView name = (TextView) findViewById(R.id.new_folder);
                String title = (String) name.getText();

                TextView descText = (TextView) findViewById(R.id.desc);
                String desc = (String) descText.getText();

                //Save it to the Word class
                ArrayList<WordFolder> word = new ArrayList<>();
                word.add(new WordFolder(title, desc));


                //goes back to the MainActivity
                Intent intent = new Intent(NewFolder.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }

In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.

Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you


回答1:


To pass data between Activities to need to do a few things:

First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.

This method takes an intent and an int. Use the same intent you used in startActivity. The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:

private static final int ADD_RESULT_CODE = 123;

Now, your button's click listener should looks something like this:

addButton.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                Intent intent=new Intent(MainActivity.this, NewFolder.class);  
                startActivityForResult(intent, ADD_RESULT_CODE);
            }  
});  

Now for returning the result. First, you shouldn't go back to your main activity by starting another intent. Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.

And to return some data, too, you can use this code:

Intent intent=new Intent();  
intent.putExtra("title",title);  
intent.putExtra("desc",desc);  
setResult(Activity.RESULT_OK, intent); 

where title and desc are the variables you want to pass.

in your case it should look something like this:

public class NewFolder extends AppCompatActivity {

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

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

    

    //If the user clicks the add button - it will save the contents to the Word Class
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //make TextView variables and cast the contents to a string and save it to a String variable
            TextView name = (TextView) findViewById(R.id.new_folder);
            String title = (String) name.getText();

            TextView descText = (TextView) findViewById(R.id.desc);
            String desc = (String) descText.getText();

            //Save it to the Word class
            ArrayList<WordFolder> word = new ArrayList<>();
            word.add(new WordFolder(title, desc));

            Intent intent=new Intent();  
            intent.putExtra("title",title);  
            intent.putExtra("desc",desc);  
            setResult(Activity.RESULT_OK, intent); 

            //goes back to the MainActivity
            finish();
        }
    });
}

You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:

setResult(Activity.RESULT_CANCELLED); 
finish();
 

In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind

Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).

To do this you need to override a method called onActivityResult inside ActivityMain:

// Call Back method  to get the Message form other Activity  
@Override  
   protected void onActivityResult(int requestCode, int resultCode, Intent data)  
   {  
             super.onActivityResult(requestCode, resultCode, data);  
             // check the result code to know where the result came from
             //and check that the result code is OK
             if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )  
             {  
                  String title = data.getStringExtra("title");  
                  String desc = data.getStringExtra("desc");  
                  //... now, do whatever you want with these variables in ActivityMain.
             }  
 }  


来源:https://stackoverflow.com/questions/63421883/how-to-dynamically-add-items-to-gridview-android-studio-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!