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

huangapple go评论56阅读模式
英文:

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

问题

你好,我想要一个Add函数,允许我向我的GridView中输入项目。

背景信息:我有一个标准的GridView和一个包含两个TextView的XML活动(我想将其转换为我的GridView)。我还有一个自定义的ArrayAdapter类和自定义的Word对象(包含两个字符串变量),帮助我实现这一点。

我的问题:我想要一个Add按钮,它可以带我到另一个XML布局/类,并且理想情况下它会输入一个单独的项目,所以当用户返回MainActivity时,GridView将被更新,以及我当前在代码中硬编码的先前信息。但是当前这个前面的句子不起作用。

自定义的ArrayAdapter和'WordFolder'是我的自定义字符串对象,它有2个getter方法。

以下是你提供的代码片段:

public class WordAdapter extends ArrayAdapter<WordFolder> {
    //构造函数 - 它接收上下文和单词列表
    WordAdapter(Context context, ArrayList<WordFolder> word){
        super(context, 0, word);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        // 视图的相关处理...
    }
}

这是你的NewFolder代码。它将contentview设置为不同的XML。因为我不知道要做什么,所以它相当空。

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);

        // 如果用户点击添加按钮 - 它将保存内容到Word类
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 处理添加按钮点击事件...
            }
        });
    }
}

在我的WordFolder类中,我创建了一些TextView变量,并将字符串保存到我的ArrayList<>对象中,但目前它毫无用处,因为它与ActivityMain中的先前ArrayList<>没有交互,这是有道理的,因为它是一个全新的对象。我考虑过将ArrayList设置为全局变量,但目前对我来说还不合适,我目前感到困惑。

如果有必要,我可以提供其他代码。谢谢。

英文:

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&lt;WordFolder&gt; 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&lt;WordFolder&gt; word = new ArrayList&lt;&gt;();
                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

得分: 0

要在活动之间传递数据,需要执行以下几个步骤:

首先,当用户按下您的“添加”按钮时,您希望以允许其返回结果的方式启动第二个活动。这意味着,您需要使用startActivityForResult而不是使用startActivity

这个方法接受一个意图和一个整数。
使用在startActivity中使用的相同意图。
整数应该是一个代码,用于在结果到达时帮助您识别结果来自何处。为此,在您的ActivityMain类中定义一些常量:

private static final int ADD_RESULT_CODE = 123;

现在,您的按钮的点击监听器应该类似于:

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

现在来返回结果。
首先,不应该通过启动另一个意图返回到主活动。
相反,您应该使用finish()(这是在AppCompatActivity中定义的一个方法,您可以使用它来“结束”活动),这将使用户返回到这个活动之前的最后位置 - ActivityMain

要返回一些数据,您可以使用以下代码:

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

其中titledesc是您要传递的变量。

在您的情况下,它应该类似于:

public class NewFolder extends AppCompatActivity {
    // ... 在onCreate方法中的其他代码

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // ... 其他代码

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

            finish();
        }
    });
}

您还应该处理用户改变主意并希望取消添加项目的情况。在这种情况下,您应该:

setResult(Activity.RESULT_CANCELED);
finish();

在您的ActivityMain中,您将拥有结果代码,如果它是Activity.RESULT_OK,您将知道应该添加一个新项,但如果是Activity.RESULT_CANCELED,您将知道用户改变了主意。

现在只剩下在ActivityMain中接收数据,并根据需要执行操作(例如将其添加到网格视图)。

要做到这一点,您需要在ActivityMain中重写一个名为onActivityResult的方法:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // 检查结果代码以了解结果来自何处
    // 并检查结果代码是否为OK
    if (resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE) {
        String title = data.getStringExtra("title");
        String desc = data.getStringExtra("desc");
        //... 现在,在ActivityMain中对这些变量执行任何您想要的操作。
    }
}
英文:

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(&quot;title&quot;,title);  
intent.putExtra(&quot;desc&quot;,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&lt;WordFolder&gt; word = new ArrayList&lt;&gt;();
            word.add(new WordFolder(title, desc));

            Intent intent=new Intent();  
            intent.putExtra(&quot;title&quot;,title);  
            intent.putExtra(&quot;desc&quot;,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 &amp;&amp; requestCode == ADD_RESULT_CODE )  
             {  
                  String title = data.getStringExtra(&quot;title&quot;);  
                  String desc = data.getStringExtra(&quot;desc&quot;);  
                  //... now, do whatever you want with these variables in ActivityMain.
             }  
 }  

huangapple
  • 本文由 发表于 2020年8月15日 09:57:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63421883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定