简体   繁体   English

如何将项目动态添加到 GridView Android Studio (Java)

[英]How to dynamically add items to GridView Android Studio (Java)

Hello I want to have an Add function that allows me to input items to my GridView您好,我想要一个 Add function 允许我将项目输入到我的 GridView

For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView.对于背景:我有一个标准 GridView 和一个 XML 活动(包含 2 个 TextView),我想将它们转换为我的 GridView。 I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.我还有一个自定义 ArrayAdapter class 和自定义 Word object (需要 2 个字符串变量)来帮助我做到这一点。

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.我的问题:我想要一个添加按钮,将我带到另一个 XML 布局/类,理想情况下它输入一个项目,因此当用户返回 MainActivity 时,GridView 将与我目前很难的先前信息一起更新-编码自动取款机。 This previous sentence doesn't work currently上一句目前不起作用

Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters自定义 ArrayAdapter 和 'WordFolder' 是我的自定义字符串 object 有 2 个吸气剂

    //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.这是我的 NewFolder 代码。 Which sets contentview to a different XML.它将 contentview 设置为不同的 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. 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.我想过让 ArrayList 成为一个全局变量,这对我来说没有意义,我现在迷路了。

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谢谢

To pass data between Activities to need to do a few things:要在Activity之间传递数据需要做几件事:

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 .这意味着,您需要使用startActivityForResult startActivity

This method takes an intent and an int.此方法需要一个意图和一个 int。 Use the same intent you used in startActivity .使用您在startActivity中使用的相同意图。 The int should be a code that helps you identify where a result came from, when a result comes. int 应该是一个代码,可以帮助您识别结果来自何处,何时出现结果。 For this, define some constant in your ActivityMain class:为此,在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.首先,您不应该通过启动另一个意图 go 回到您的主要活动。 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 .相反,您应该使用finish() (这是在AppCompatActivity中定义的方法,您可以使用它来finish您的活动),这会将用户返回到他在此活动之前的最后一个位置 - 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.其中 title 和 desc 是您要传递的变量。

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在您的ActivityMain中,您将获得结果代码,如果它的Activity.RESULT_OK你会知道你应该添加一个新项目,但如果它的Activity.RESULT_CANCELLED你会知道用户改变了主意

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).现在剩下的就是在 ActivityMain 中接收数据,然后做任何你想做的事情(比如将它添加到网格视图中)。

To do this you need to override a method called onActivityResult inside ActivityMain :为此,您需要在ActivityMain中覆盖一个名为onActivityResult的方法:

// 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.
             }  
 }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM