首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在同一个片段中的另一个函数中使用一个函数中的数组

在同一个片段中的另一个函数中使用一个函数中的数组
EN

Stack Overflow用户
提问于 2021-04-19 16:12:12
回答 1查看 41关注 0票数 1

我是java新手,正在尝试在一个函数中使用sampleTitles,并在另一个函数中使用。sampleTitles中的数据是动态的,并且是从改造中提取的

Fragment.java

代码语言:javascript
运行
复制
@BindView(R.id.customCarouselView) CarouselView customCarouselView; //butterknife

double[] sampleVotes = {
    8.9,4.2,
};

@Override
public void onCreate (@Nullable Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    
    connect();
}

private void connect() {

    //this array not passed to setViewListener 
    String[] sampleTitles = {
                "Test 1",
                "Test 2",
    };
                        
    customCarouselView.setViewListener(viewListener);
}

// To set custom views
ViewListener viewListener = new ViewListener() {
    @Override
    public View setViewForPosition(int position) {

        View customView = getLayoutInflater().inflate(R.layout.view_custom, null);

        TextView labelTextView = customView.findViewById(R.id.labelTextView);
        labelTextView.setText(sampleTitles[position]);  //want to use sampleTitles here from 
        connect(); function               

        return customView;
    }
};
EN

Stack Overflow用户

回答已采纳

发布于 2021-04-19 16:20:34

使该数组成为全局变量。所以你可以通过整个类来访问它。如下所示更改您的代码。另外,我建议你改用ArrayList,这样你就不需要在初始化时提供数组的大小了。如果你遇到任何问题,请告诉我。

代码语言:javascript
运行
复制
 @BindView(R.id.customCarouselView) CarouselView customCarouselView; //butterknife


   double[] sampleVotes = {
            8.9,4.2,
    };

    List<String> sampleTitles = new ArrayList<String>(); //declare as global variable so you can access it

    @Override
        public void onCreate (@Nullable Bundle savedInstanceState) {
            super.onCreate (savedInstanceState);
    
    connect();
    }

   private void connect() {

    //Do your insert operations in array here 
        sampleTitles.add("Test 1");
        sampleTitles.add("Test 2");
                        
        customCarouselView.setViewListener(viewListener);

    }

   // To set custom views
    ViewListener viewListener = new ViewListener() {
        @Override
        public View setViewForPosition(int position) {

            View customView = getLayoutInflater().inflate(R.layout.view_custom, null);

            TextView labelTextView = customView.findViewById(R.id.labelTextView);
          
            labelTextView.setText(sampleTitles.get(position));  //you can access your array with this code               

            return customView;
        }
    };
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67158238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档