代码之家  ›  专栏  ›  技术社区  ›  Sonny P.

将ArrayList<Character>或<Integer>从一个类传输到activity类

  •  0
  • Sonny P.  · 技术社区  · 2 年前

    我正在尝试将此代码从一个类传输到Android Studio中的一个活动类,因为我正在尝试将其用于文本视图。

    public class cartesian() {
        public ArrayList<Character> list1() {
            Random rand = new Random();
            int low = 3;
            int high = 5;
            int result = rand.nextInt(high - low) + low;
    
            ArrayList<Character> list1 = new ArrayList<>(result);
    
            for (int i = 0; i <= result; i++) {
                list1.add((char)(rand.nextInt(26) + 'a'));
            }
    
            return list1;
        }
    
        public ArrayList<Integer> list2() {
            Random rand = new Random();
            int low = 3;
            int high = 5;
            int result = rand.nextInt(high - low) + low;
    
            ArrayList<Integer> list2 = new ArrayList<>(result);
    
            for (int i = 0; i <= result; i++) {
                list2.add(rand.nextInt(100));
            }
    
            return list2;
        }
    }
    

    我已经尝试了 here ,由“ 巴斯蒂安·皮纳基 “但这也不起作用,因为它每次都返回null。我也尝试过使用自定义对象,但我对自己对它的理解没有信心,无法充分利用它。

    自定义对象类

    public class CustomObject {
        private List<Character> charList;
        private List<Integer> intList;
    
        public CustomObject(){
            // not sure if I need to put anything in here
        }
    
        public List<Character> getCharList() { return charList; }
        public void setCharList(List<Character> charList) { this.charList = charList; }
        public List<Integer> getIntList() { return intList; }
        public void setIntList(List<Integer> intList) { this.intList = intList; }
    }
    

    活动类别

    public class cartProdActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart_prod);
        
        ArrayList<Character> charList = list1();
        String charListStr = charList.toString();
    
        ArrayList<Integer> intList = list2();
        String intListStr = intList.toString();
    
        setTxt(charListStr, intListStr);
    }
    
    public void setTxt(String list1, String list2) {
        TextView list1View = (TextView) findViewById(R.id.list1);
        list1View.setText(list1);
    
        TextView list2View = (TextView) findViewById(R.id.list2);
        list2View.setText(list2);
    }
    // the list1 and list2 functions refer to the functions from the first code block
    // they are there as I was testing whether the code was working or not
    

    函数本身的工作方式与我将其放在activity类中进行检查的方式相同,但我希望它放在一个单独的类中,我需要为其他目的使用列表本身。

    0 回复  |  直到 2 年前